简体   繁体   English

req.files 总是使用 express-fileupload 和 body-parser 返回 undefined

[英]req.files always returns undefined with express-fileupload and body-parser

I am working on an assignment where I am to upload a file to a NodeJs server.我正在完成一项任务,将文件上传到 NodeJs 服务器。 Every time I hit the POST request on the server, req.files always returns undefined and I am not sure why.每次我在服务器上发出 POST 请求时,req.files 总是返回 undefined,我不知道为什么。 I am assuming that this has to do with what I am sending in the body of the request, but I guess I am not sure what exactly I need to send.我假设这与我在请求正文中发送的内容有关,但我想我不确定我到底需要发送什么。 I've read that body-parser only works with JSON objects, but even with that, the server still returns undefined.我读过 body-parser 只适用于 JSON 对象,但即使如此,服务器仍然返回 undefined。 Any suggestions?有什么建议?

Here is the relevant code for both the client, server, and database files that I am working with:这是我正在使用的客户端、服务器和数据库文件的相关代码:

admin.html (body): 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 (script): 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:服务器.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);})})

You need to encode your data as "multipart/form-data" instead of "json".您需要将数据编码为“multipart/form-data”而不是“json”。

Quick example:快速示例:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM