如何使用提取上传文件

时间:2019-03-22 17:26:19

标签: javascript reactjs fetch

我知道之前已经有人问过这个问题,但是没有一个解决方案对我有用。首先,我尝试使用axios来解决此问题,但是阅读它似乎存在一个错误,该错误使我无法使用它来上传文件。所以我坚持使用fetch

这是我的上传功能:

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));
}

这就是我的称呼:

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))
    }

我知道file实际上是一个文件。每当我将"pdf"更改为普通字符串时,一切正常。但是,当我使用File对象时,后端没有任何东西,只有一个空对象。我在这里想念什么?我觉得我的解决方案与我在网上找到的所有其他解决方案基本相同。

编辑: 还尝试使用FormData并将headers: {"Content-Type": "application/x-www-form-urlencoded"}添加到选项中。结果相同。

编辑2 我开始认为我的后端可能是问题所在!这是我的后端,实际上我为“数据”事件得到了一些输出。不确定如何处理...

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);
    })
});

3 个答案:

答案 0 :(得分:0)

您应将FormData'Content-Type': 'application/x-www-form-urlencoded'一起用作提取标头。

答案 1 :(得分:0)

我希望您尝试一种简单的方法。而不是将文件附加到FormData中,而是创建实际表单的实例。

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> 

在更改文件输入时,它将触发表单提交(onStudyPlanUpload)。

希望这会起作用!

答案 2 :(得分:0)

我会回答我自己的问题。如果其他人遇到此问题,则是 BACKEND 有问题。这是我使用busboy处理传入表单数据的最终解决方案。我没有更改服务器上的任何内容,但必须更新路由器。这是我的路由器,负责POST请求:

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;

最后,我完成了onStydyPlanUpload()函数!

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))

}

获得了https://gist.github.com/shobhitg/5b367f01b6daf46a0287

的帮助