I am trying to upload files to a list item that I am creating using SPFX. I have to do this on a SharePoint 2019 server and I am not using any libraries like React. Below is the code I use to upload the files. It works great with one exception. I can't get the file to upload without metadata. A simple text file with the word "Test" in it will be uploaded and look like this when you open it.
------WebKitFormBoundary7ZlPVABRPJrQ1qjn Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain test ------WebKitFormBoundary7ZlPVABRPJrQ1qjn--
Below is the code that I am using. I think I need to add something to the headers or body, but not sure what to add.
private async uploadFile(file: File, itemId: number): Promise<void> {
const formData = new FormData();
formData.append("file", file, file.name);
const response = await this.context.spHttpClient.post(
`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('MyListName')/items(${itemId})/AttachmentFiles/add(FileName='${file.name}')`,
SPHttpClient.configurations.v1,
{
headers: [
["Accept", "application/json; odata=verbose"],
["content-type", "application/json;odata=nometadata"],
],
body: formData,
}
);
if (!response.ok) {
throw new Error("Error uploading file: " + file.name);
}
}
PLEASE HELP!
UPDATE: I found this post: SPFX File upload to List
This seems to work if I don't use FormData and just use "body: file" in the spHttpClient options. FormData should've worked though. Anyone know why?