I am developing a website by using Next.js and trying to upload a file to OneDrive by using Microsoft Graph REST API.
The document says the request body should be the binary stream of the file to be uploaded, but I don't know how to convert it to binary stream.
I am using HTML input element to save file data to file:
{name: '200311 Weekly Safety Meeting - Coronavirus (2019-nCoV).pdf', lastModified: 1644421523745, lastModifiedDate: Wed Feb 09 2022 07:45:23 GMT-0800 (Pacific Standard Time), webkitRelativePath: '', size: 700913, …}
My code on the client side,
const uploadFile = async () => {
const res = await axios.put('/api/onedrive/file', {
accessToken: token,
filename: file.name,
content: file,
parentId: '01XA3PFKG7YWH2K7QVIZCYRP33XLQEHLZG',
});
console.log(res.data);
};
On the server side,
const upload = async (req, res) => {
const { filename, accessToken, content, parentId } = req.body;
const url = `https://graph.microsoft.com/v1.0/users/69e5bc0d-ef63-4040-88cf-0ada867b7afa/drive/items/${parentId}:/${filename}:/content`;
try {
const result = await axios({
method: 'put',
url: url,
body: content,
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
res.status(200).send(result.data);
} catch (err) {
console.log(err);
res.status(500).send(err);
}};
Thanks for reaching out
Please try the below code for converting file into binary format, see if it works
Code:
function GetBinaryDataFromFile(strFileName)
{
var fso = new ActiveXObject("ADODB.Stream");
fso.Type = 1
fso.Open
fso.LoadFromFile strFileName
}