@pnp/sp 1.1.0
I have an ExpressJS server which implements a REST Api that upload files to Sharepoint.
The problem is that i'm unable to upload the file received via my custom API to SharePoint.
I've tried to parse the file to both ArrayBuffer and Base64 string, but the response of _sp.web.getFolderByServerRelativeUrl(myUrl).files.add_ is always the same: -1, System.IO.IOException - I/O error occurred.
This is my API code:
apiApp.post('/Documentos', upload.single('file'), (request, response) => {
const file = request.file;
const meta = request.body;
const parsedFile = file.buffer; // i've tried file.buffer.toString('Base64') too
sp.web.getFolderByServerRelativeUrl(documentosUrl).files.add(meta.name, parsedFile, true)
.then(result => response.send(result))
.catch((err) => {
console.error('Ocorreu um erro', err)
response.status(500).send(err)
})
})
In the client, this is the call to the API:
addDocumento(file) {
let data = new FormData();
data.append('file', file);
data.append('name', file.name);
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
return Api().post('Documentos', data, config)
}
Thanks in advance!
Hi @Jonas-buriti ,
I don't know what all you are doing with the uploaded file, but in my testing I can upload files both as text and buffers from node using the code below. If you supply the encoding you can get a text file and if you omit it you get back the raw buffer. Both worked in my testing for uploading files to SharePoint. I'd suggest trying to determine exactly what the type of "request.file" actually is and that might give you some insight into what is happening.
// fs.readFile(filePath, { encoding: "utf-8" }, (err, data) => {
fs.readFile(filePath, (err, data) => {
if (!err) {
sp.web.getFolderByServerRelativeUrl("/sites/dev/Shared%20Documents").files.add("jscore-release-slide.png", data, true).then(_ => {
console.log("done");
});
} else {
console.log(err);
}
});
Hi @patrick-rodgers!
Thank you for the answer, that gave me a insight about the problem!
When I tried to use the fs, to read and upload a local file, I noticed that the requests were failing only with buffers.
So I added the Content-Length header, and finally was able to add files from buffers:
sp.setup({
sp: {
fetchClientFactory: () => {
return new NodeFetchClient(spCredentials, siteUrl);
},
headers: {
"Accept": "application/json; odata=verbose",
"Content-Length": fileData.length
}
},
});
Most helpful comment
Hi @Jonas-buriti ,
I don't know what all you are doing with the uploaded file, but in my testing I can upload files both as text and buffers from node using the code below. If you supply the encoding you can get a text file and if you omit it you get back the raw buffer. Both worked in my testing for uploading files to SharePoint. I'd suggest trying to determine exactly what the type of "request.file" actually is and that might give you some insight into what is happening.