Как загрузить файл на сервер, с помощью multer?
Когда я отправляю файл на сервер, то получаю пустой объект, хотя делаю все по видео.
- Если использовать с FileReader
Фронт
<template>
<form @submit.prevent="load" enctype="multipart/form-data">
<input
@change="loadFile($event)"
type="file"
name="image"
accept="image/*"
/>
<input type="submit" value="submit" />
</form>
</template>
<script>
export default {
data() {
return {
image: {},
};
},
methods: {
loadFile(e) {
if (window.FileReader && window.File) {
const file = e.currentTarget.files[0];
const reader = new FileReader();
if (file && reader) {
reader.readAsDataURL(file);
reader.addEventListener("error", (err) => {
throw err;
});
reader.addEventListener("load", () => {
this.image = { res: reader.result, file };
});
} else {
this.image = {
res: "",
file: {},
};
}
}
},
load() {
if (Object.keys(this.image).length) {
// { res: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pjxz...', file: { lastModified: 1638642563466, ... } }
console.log(this.image);
const res = fetch("http://localhost:3000/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept-Type": "application/json",
},
body: JSON.stringify({ image: this.image }),
});
res
.then((data) => console.log(data))
.catch((err) => {
throw err;
});
}
},
},
};
</script>
Сервер
const express = require('express');
const app = express();
const path = require('path');
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.resolve(__dirname, '../uploads'))
},
filename: (req, file, cb) => {
console.log(file);
cb(null, `${file.originalname}-${Date.now()}`);
}
});
const upload = multer({ storage });
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/upload', upload.single('image'), (req, res) => {
// Приходит пустой файл
// { image: { res: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4...', file: {} } }
console.log(req.body);
return res.status(200).json({ ok: true });
});
module.exports = app;
- Если использовать FormData
Фронт
<template>
<form @submit.prevent="load" enctype="multipart/form-data">
<input
@change="loadFile($event)"
type="file"
name="image"
accept="image/*"
/>
<input type="submit" value="submit" />
</form>
</template>
<script>
export default {
data() {
return {
image: {},
};
},
methods: {
loadFile(e) {
const file = e.currentTarget.files[0];
if (file) {
this.image = file;
}
},
load() {
if (Object.keys(this.image).length) {
const fd = new FormData();
fd.append("image", this.image);
const res = fetch("http://localhost:3000/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept-Type": "application/json",
},
body: JSON.stringify(fd),
});
res
.then((data) => console.log(data))
.catch((err) => {
throw err;
});
}
},
},
};
</script>
Сервер
const express = require('express');
const app = express();
const path = require('path');
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.resolve(__dirname, '../uploads'))
},
filename: (req, file, cb) => {
console.log(file);
cb(null, `${file.originalname}-${Date.now()}`);
}
});
const upload = multer({ storage });
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/upload', upload.single('image'), (req, res) => {
// Приходит объект
// {}
console.log(req.body);
return res.status(200).json({ ok: true });
});
module.exports = app;