I know this has been asked before, but none of the solutions are working for me. First I tried to solve this using axios
, but reading about it there seem to be a bug that won't allow me to use it for uploading files. So I'm stuck with fetch
.
This is my uploading function:
export async function postStudyPlan(plan, headers) {
const options = {
method: "POST",
body: plan
}
return fetch(`${HOST}:${PORT}/study-plans/add`, options)
.then(res => {return res.json()})
.catch(err => console.log(err));
}
This is how I call it:
onStudyPlanUpload(files) {
const file = files[0];
let formData = new FormData();
formData.append("pdf", file);
formData.append("comments", "A really lit study plan!");
formData.append("approved", true);
formData.append("uploaded_by", "Name");
formData.append("date_uploaded", "2012-02-1");
formData.append("university", "australian_national_university");
let plan = {
"pdf": file,
"comments": "A really lit study plan!",
"approved": true,
"uploaded_by": "Name",
"date_uploaded": Date.now(),
"university": "australian_national_university"
}
postStudyPlan(formData)
.then(res => console.log(res))
.catch(err => console.log(err))
}
I know that file
is in fact a file. Whenever I change "pdf"
to a normal string, everything works fine. But when I use a File
object, I recieve nothing to my backend, just an empty object. What am I missing here? I feel like my solution is basically identical to every other solution I've found online.
Edit:
Also tried using FormData and adding headers: {"Content-Type": "application/x-www-form-urlencoded"}
to options. Same result.
Edit 2 I'm beginning to think my backend might be the problem! This is my backend, and I'm actually getting some outputs for the "data" event. Not sure how to process it...
router.route("/add").post((req, res) => {
req.on("data", function(data) {
console.log("got data: " + data.length);
console.log("the Data: ?" )
// let t = new Test(data);
// t.save()
// .then(res => console.log(res))
})
req.on("end", function(d) {
console.log("ending!");
})
req.on("error", function(e){
console.log("ERROR: " + e);
})
});