简体   繁体   中英

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. Every time I hit the POST request on the server, req.files always returns undefined and I am not sure why. 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. Any suggestions?

Here is the relevant code for both the client, server, and database files that I am working with:

admin.html (body):

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

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

You need to encode your data as "multipart/form-data" instead of "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,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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