D
D
dicem2019-07-31 13:19:00
Express.js
dicem, 2019-07-31 13:19:00

Why are the files not uploading to the server?

Hello, I apologize in advance for the tags, because I don’t understand on which side the error is on this issue.
So. I made a front on vue cli and I use express and express-fileupload
to upload images Form on the front:

Poke here

Это собственно инпут сам
<div class="form-group">
  <label>Изображение</label>
  <input type="file" class="form-control-file" @change="handleFileUpload($event)">
</div>

А это обработчик @change
handleFileUpload(e) {
        this.file = e.target.files[0]

        this.submitFile()
      },
      submitFile() {
        fetch('http://localhost:3000/upload/', {
          method: 'post',
          body: this.file
        })
          .then( response => response.json())
          .then( success => console.log(success))
          .catch( err => console.log(err))
      }


The server for uploading files was made according to the following lesson: https://www.youtube.com/watch?v=WLEtj-iZL3g&t=1s
However, along the way I found an example on the express-fileupload plugin and made the following code:
The code

const express = require('express');
const fileUpload = require('../lib/index');
const app = express();

const PORT = 8000;
app.use('/form', express.static(__dirname + '/index.html'));

// default options
app.use(fileUpload());

app.get('/ping', function(req, res) {
  res.send('pong');
});

app.post('/upload', function(req, res) {
  let sampleFile;
  let uploadPath;

  if (Object.keys(req.files).length == 0) {
    res.status(400).send('No files were uploaded.');
    return;
  }

  console.log('req.files >>>', req.files); // eslint-disable-line

  sampleFile = req.files.sampleFile;

  uploadPath = __dirname + '/uploads/' + sampleFile.name;

  sampleFile.mv(uploadPath, function(err) {
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded to ' + uploadPath);
  });
});

app.listen(PORT, function() {
  console.log('Express server listening on port ', PORT); // eslint-disable-line
});


I still don’t understand, the files are not uploaded, when I tested it and put the usual one on the post, console.log(req.files)I got undefined every time I tried to upload files.
Please help!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-07-31
@dicem

const data = new FormData();
data.append('sampleFile', this.file);

fetch('http://localhost:3000/upload/', {
  method: 'post',
  body: data,
})

UPD. Well, it's not very clear why the file needs to be a property of the component. Why not make it a parameter of the submitFile method?
@change="submitFile($event.target.files[0])"
methods: {
  submitFile(file) {
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question