Multer 不创建文件
我在使用 multer 创建文件时遇到问题。
文件架构:
My app folder
Back
config
-config.json
images
middleware
-auth.js
-multer-config.js
migrations
-create-user.js
-create-message.js
models
-index.js
-message.js
-user.js
node_modules
routes
-posts.js
-users.js
-.env
-app.js
-server.js
-package.json
-package-lock.json
Front
--some files
前面:
async handleSubmit() {
var formData = new FormData();
formData.append('image', this.file[0]);
await fetch("http://localhost:3000/api/sendTest",{
method: 'POST',
body: formData,
headers:{"content-type": "multipart/form-data; boundary=image", "authorization": this.$store.state.jwt}
});
}
后面(/back/routes/posts.js):
const express = require('express');
const router = express.Router();
var models = require('../models');
const auth = require('../middleware/auth');
const multer = require('../middleware/multer-config');
router.post('/sendTest', auth, multer, async (req, res, next) => {
try {
console.log(req.file); // return undefined
res.status(201).json({
message: 'Message publié'
});
} catch (err) {
res.status(400).json({ message: err.original.sqlMessage });
}
});
后面(/back/app.js):multer-config:console.log(this.file[0
const express = require('express');
const app = express();
const helmet = require('helmet');
const path = require('path');
app.use(helmet());
// Routage
const postsRoutes = require("./routes/posts");
const usersRoutes = require("./routes/users");
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(express.json());
app.use('/api', express.static(path.join(__dirname, 'images')));
app.use('/api', postsRoutes);
app.use('/api', usersRoutes);
module.exports = app;
]
const multer = require('multer');
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif'
};
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'images');
},
filename: (req, file, callback) => {
const name = file.originalname.split(' ').join('_');
const extension = MIME_TYPES[file.mimetype];
callback(null, name + Date.now() + '.' + extension);
}
});
module.exports = multer({storage: storage}).single('images');
)从前面返回:
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }
console.log( formData) 从前面返回:
FormData { }
但是,这是正常的,我们必须使用键:
for (var [key, value] of formData.entries()) {
console.log(key, value);
}
returns
image
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }
因此,我认为 Front 发送的文件格式很好。
据我了解,multer 必须在“/back/images”中创建文件,然后我们应该能够在路由“/sendTest”中使用 req.file,但它返回未定义。
我正在使用sequelize 连接到数据库。
我不确定是否在“auth”之后调用 multer,因为当我发送请求时,multer-config 中的 console.log(“test”) 应该显示在控制台“test”中,控制台中什么也没有出现,除非我更改后保存“multer-config”文件。
如果有人知道如何解决问题或在某个地方看到错误,我很感兴趣!
I have a problem with file creation with multer.
File architecture:
My app folder
Back
config
-config.json
images
middleware
-auth.js
-multer-config.js
migrations
-create-user.js
-create-message.js
models
-index.js
-message.js
-user.js
node_modules
routes
-posts.js
-users.js
-.env
-app.js
-server.js
-package.json
-package-lock.json
Front
--some files
Front:
async handleSubmit() {
var formData = new FormData();
formData.append('image', this.file[0]);
await fetch("http://localhost:3000/api/sendTest",{
method: 'POST',
body: formData,
headers:{"content-type": "multipart/form-data; boundary=image", "authorization": this.$store.state.jwt}
});
}
Back (/back/routes/posts.js):
const express = require('express');
const router = express.Router();
var models = require('../models');
const auth = require('../middleware/auth');
const multer = require('../middleware/multer-config');
router.post('/sendTest', auth, multer, async (req, res, next) => {
try {
console.log(req.file); // return undefined
res.status(201).json({
message: 'Message publié'
});
} catch (err) {
res.status(400).json({ message: err.original.sqlMessage });
}
});
Back (/back/app.js):
const express = require('express');
const app = express();
const helmet = require('helmet');
const path = require('path');
app.use(helmet());
// Routage
const postsRoutes = require("./routes/posts");
const usersRoutes = require("./routes/users");
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(express.json());
app.use('/api', express.static(path.join(__dirname, 'images')));
app.use('/api', postsRoutes);
app.use('/api', usersRoutes);
module.exports = app;
multer-config:
const multer = require('multer');
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif'
};
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'images');
},
filename: (req, file, callback) => {
const name = file.originalname.split(' ').join('_');
const extension = MIME_TYPES[file.mimetype];
callback(null, name + Date.now() + '.' + extension);
}
});
module.exports = multer({storage: storage}).single('images');
console.log(this.file[0]) from front returns :
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }
console.log(formData) from front returns :
FormData { }
But, that's normal, we have to use keys:
for (var [key, value] of formData.entries()) {
console.log(key, value);
}
returns
image
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }
We can see the request in Network
I think the file format sent from Front is therefore good.
As i understand multer has to create the file in "/back/images" and then we should be able to use req.file in the route "/sendTest" but it returns undefined.
I'm using sequelize to connect to database.
I'm not sure if multer is called after "auth" because a console.log("test") in multer-config should display in the console "test" when I send my request, nothing appears in the console, except when I save the "multer-config" file after a change.
If anyone has an idea of how to fix the problem or sees an error somewhere, I'm interested!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现错误:
返回(/back/app.js):
替换
为
前面:
删除标题内容类型:
然后现在文件已上传!
希望它对你有用:)
I found errors:
Back (/back/app.js):
replace
by
Front:
Remove headers content-type:
Then now files are uploaded !
Hope it be useful for you :)