req.files始终使用express-fileupload和body-parser返回未定义的

时间:2020-03-29 22:37:32

标签: javascript node.js express post file-upload

我正在做一个分配,将文件上传到NodeJs服务器。每当我在服务器上命中POST请求时,req.files总是返回undefined,我不确定为什么。我假设这与我在请求正文中发送的内容有关,但是我想我不确定我到底需要发送什么。我读过body-parser仅适用于JSON对象,但即使这样,服务器仍返回未定义。有什么建议吗?

以下是我正在使用的客户端,服务器和数据库文件的相关代码:

admin.html(正文):

    <div style="display: none; margin-bottom: 6%;" id="part2B">
        <label for="fileSelect2">Step 2: Upload a new image:  </label>
        <input type="file" id="fileSelect2" name="uploadFile2" value="" accept="image/*" onchange="fileSelected(event)">
    </div>

admin.html(脚本):

       function fileLoaded(event) {
            var image = new Image();
            image.onload = imageLoaded;
            image.src = event.target.result;
            let data = document.getElementById("fileSelect2").files[0]
            fetchThemes().
            then(tableOfContents => {
                for (let theme of tableOfContents){
                    if (theme['name'] == document.getElementById("selectThemeInput").value){
                        fetch(host+'/image/:'+theme['id'], {
                            mode: 'cors',
                            method: 'POST',
                            body: JSON.stringify(data)
                        })
                    }
                }
            })
        }

server.js:

    // dependencies
       const fileUpload = require('express-fileupload')
       const bodyParser = require('body-parser')
       const express = require('express');
       const url = require('url');
       var cors = require('cors');

       const db = require('./db-001.js');

     //create the server
      const app = express();
      const port = 3002;


     // parse application/json
        app.use(bodyParser.json())
        app.use(cors())
        app.use(fileUpload())

      app.post('/image/:themeId', (request, response) => {
           console.log(request.files)
           let imageFile = request.files.image;
           db.saveImage(request.params.themeId)
             .then(image => {imageFile.mv('./data/' + image.name);})})

1 个答案:

答案 0 :(得分:0)

您需要将数据编码为“ multipart / form-data”,而不是“ json”。

快速示例:

const fileInput = document.querySelector('#your-file-input') ;
const formData = new FormData();

formData.append('file', fileInput.files[0]);

const options = {
  method: 'POST',
  body: formData,
};