Answer the question
In order to leave comments, you need to log in
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:
<div class="form-group">
<label>Изображение</label>
<input type="file" class="form-control-file" @change="handleFileUpload($event)">
</div>
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))
}
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
});
console.log(req.files)
I got undefined every time I tried to upload files. Answer the question
In order to leave comments, you need to log in
const data = new FormData();
data.append('sampleFile', this.file);
fetch('http://localhost:3000/upload/', {
method: 'post',
body: data,
})
@change="submitFile($event.target.files[0])"
methods: {
submitFile(file) {
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question