I am sending a http request with a file to Sharepoint. Some file types, such as png or other images become corrupted and unreadable. When looking at those I see extra object data at the head e.g.
----------------------------826320949470377643449533 Content-Disposition: form-data; name="file"; filename="mypdf.pdf" Content-Type: application/pdf
and at the bottom:
----------------------------826320949470377643449533--
Is there a way to prevent this? The code I am using looks like:
const contentType = mime.contentType(fileName);
const data = new FormData();
data.append('file',fs.createReadStream(path));
const fileSize = req.headers['content-length']
fs.promises.file(file)).size
const fileSizeLessByte = fileSize-1;
const contentRange = 'bytes 0-'+fileSizeLessByte+'/'+fileSize;
const contentLength = fileSize;
var config = {
method: 'put',
url: uploadUrl,
headers: {
'Content-Range': contentRange,
'Content-Length': contentLength,
'Content-Type': 'multipart/form-data'
},
data : data
};
Advertisement
Answer
I was eventually able to get this working by using readFileSync instead of FormData and not using the multipart content type as O. Jones suggested:
const contentType = mime.contentType(fileName);
const fileStream = fs.readFileSync(path);
const fileSize = Buffer.byteLength(fileStream);
const fileSizeLessByte = fileSize-1
const contentRange = 'bytes 0-'+fileSizeLessByte+'/'+fileSize;
const contentLength = fileSize;
const config = {
method: 'put',
url: uploadUrl,
headers: {
'Content-Type': contentType,
'Content-Range': contentRange,
'Content-Length': contentLength
},
data: fileStream
};