0

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);
    })
});
Zorobay
  • 557
  • 1
  • 6
  • 23

3 Answers3

0

You should use FormData with 'Content-Type': 'application/x-www-form-urlencoded' as fetch header.

Prabu samvel
  • 1,213
  • 8
  • 19
0

I want you to try a simple approach. Instead of appending the file into FormData, create an instance of an actual form.

onStudyPlanUpload = (event) => {
  event.preventDefault();
  const formData = new FormData(event.target);
  postStudyPlan(formData)
        .then(res => console.log(res))
        .catch(err => console.log(err))
}

HTML

<form onSubmit={this.onStudyPlanUpload} encType="multipart/form-data" ref={el => this.form = el}>
 <input type="file" name="pdf" onChange={() => { this.form.dispatch(new Event('submit'))}/>
 <input type="hidden" name="comments" value="A really lit study plan!" />
 <input type="hidden" name="approved" value=true />
 <input type="hidden" name="uploaded_by" value="Name"/>
 <input type="hidden" name="date_uploaded" value="2012-02-1"/>
 <input type="hidden" name="university" value="australian_national_university"/>
</form> 

While changing the file input, It will trigger the form submit (onStudyPlanUpload).

Hope this will work!

Prabu samvel
  • 1,213
  • 8
  • 19
0

I'll answer my own question. If anyone else comes across this problem, it is the BACKEND that's faulty. This is my final solution using busboy to handle incoming form data. I didn't change anything on my server, but my router had to be updated. Here is my router, taking care of POST requests:

const express = require("express");
const mongoose = require("mongoose");
require('./../../models/Test');
const path = require("path");
const fs = require("fs");
const router = express.Router();

const Busboy = require("busboy");

router.route("/add").post((req, res, next) => {
    let busboy = new Busboy({headers: req.headers});

    // A field was recieved
    busboy.on('field', function (fieldname, val, valTruncated, keyTruncated) {

        if (req.body.hasOwnProperty(fieldname)) { // Handle arrays
            if (Array.isArray(req.body[fieldname])) {
                req.body[fieldname].push(val);
            } else {
                req.body[fieldname] = [req.body[fieldname], val];
            }
        } else { // Else, add field and value to body
            req.body[fieldname] = val;
            console.log(req.body);
        }
    });

    // A file was recieved
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log("File incoming: " + filename);
        var saveTo = path.join('.', filename);
        console.log('Uploading: ' + saveTo);
        file.pipe(fs.createWriteStream(saveTo));
    });

    // We're done here boys!
    busboy.on('finish', function () {
        console.log('Upload complete');
        res.end("That's all folks!");
    });
    return req.pipe(busboy);
});

module.exports = router;

Finally, my finished onStydyPlanUpload() function!

onStudyPlanUpload(files) {

    const file = files[0];
    let formData = new FormData();

    formData.append("pdf", file, file.name);
    formData.append("comments", "A really lit study plan!");
    formData.append("approved", true);
    formData.append("uploaded_by", "Melker's mamma");
    formData.append("date_uploaded", new Date());
    formData.append("university", "australian_national_university");

    const HOST = "http://localhost";
    const PORT = 4000;
    axios.post(`${HOST}:${PORT}/test/add`, formData)
        .then(res => console.log(res))
        .catch(err => console.log(err))

}

Got help from: https://gist.github.com/shobhitg/5b367f01b6daf46a0287

Zorobay
  • 557
  • 1
  • 6
  • 23