我完全没死了 . 几个小时以来,我一直在寻找答案,但似乎无法得到任何工作 .

  • React app

  • 用于AJAX的Axios

  • 尝试使用multer将文件发布到Express endpoints .

我的终点:

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });


router.post("/", upload.single("file"), async (req, res) => {
    let file = req.file.buffer; //...file is undefined from Axios, has buffer from Postman and works
    //...etc...
});

我的表格:

onChangeFile = e => {
    let file = e.target.files[0];
    let formData = new FormData();
    formData.append("file", formData);
    const reqParams = {
        method: "POST",
        url: `https://myapi.com/documents`,
        data: {
            "file": formData
        },
        headers: {
            "my_custom_header": "ABC123"
        }
    };
    axios(reqParams)
        .then(result => console.log(JSON.stringify(result, null, 4)))
        .catch(e => console.log(e));
}

render() {
    <form encType="multipart/form-data">
        <input type="file" name="file" id="file" onChange={this.onChangeFile} />
    </form>
}

上面的Axios结果输出:

{
    "data": [
        {
            "source": "system",
            "type": "json",
            "status": 200,
            "reason": null,
            "message": "Successful",
            "error": false,
            "date": "2018-08-28T21:35:36.000Z",
            "payload": {
                "my_custom_header": "ABC123",
                "file": {}
            }
        }
    ],
    "status": 200,
    "statusText": "OK",
    "headers": {
        "content-type": "application/json; charset=utf-8"
    },
    "config": {
        "transformRequest": {},
        "transformResponse": {},
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8",
            "my_custom_header": "ABC123"
        },
        "method": "post",
        "url": "https://myapi.com/documents",
        "data": "{\"file\":{}}"
    },
    "request": {}
}

endpoints 在Postman上运行得很好 . 我最初跟着这篇文章:https://blog.stvmlbrn.com/2017/12/17/upload-files-using-react-to-node-express-server.html