Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I'm using react dropzone to upload files. It works with .txt files but pdfs(and docx) gets corrupted.
Does this looks correct? I have attached the files I'm using to test.
onDrop = (acceptedFiles, rejectedFiles) => {
let file = acceptedFiles[0];
let filename = file.name;
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onabort = () => console.log('file reading was aborted')
reader.onerror = () => console.log('file reading has failed')
reader.onload = () => {
const binaryStr = reader.result;
axios.post('/jsonapi/node/application/field_resume',
binaryStr
, {
headers: {
"Content-Type": "application/octet-stream",
"Accept": "application/vnd.api+json",
"Content-Disposition": 'file; filename="' + filename + '"',
'X-CSRF-Token': "HDel-LIL4o709vjgAW6N82Me5wiJ1ZHu_7KHaXN19Vo",
}
}
)
.then((response) => {
console.log(response);
})
.catch(function (error) {
console.log(error);
}.bind(this));
}
};
Comments
Comment #2
Wim LeersI'm pretty sure people have been uploading images. And if textual files work, then binary files ought to work too. Are you sure you're using
axios
correctly?Comment #3
frega CreditAttribution: frega as a volunteer commentedHi,
this sounds very like this axios-issue https://github.com/axios/axios/issues/1250#issuecomment-391968564 which indicates that `readAsArrayBuffer` should be used instead of `readAsBinaryString`. The issue also points to the documentation at https://github.com/axios/axios#request-config where the docblock above the `transformRequest` functions specs that `The last function in the array [transforming the request] must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream`.
Could you try to see if that resolves the issue?
Best, Fredrik
Comment #4
Wim LeersThanks for doing the work to write that insightful comment, @frega! 🙏
Comment #5
Hygglo CreditAttribution: Hygglo commentedThank you so much! That solved the problem!
See working example below. Hopefully iy can help someone else in the future.
Comment #6
Wim LeersAwesome! :) Thanks @frega, and thanks for confirming so quickly, @Hygglo!
Comment #8
camoz CreditAttribution: camoz commentedthanks Hygglo, I spent 2-3 hours looking for this solution. cheers