我想使用Node Js上传产品图像。所以我用multer上传图片。我用邮递员测试它是否有用,但它返回Please upload a file
。我改变了另一张图像然后它说PayloadTooLargeError: request entity too large
。
mycode的
const express = require("express");
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage(
{
destination: function(req, file, cb)
{
cb(null, './uploads/');
},
filename: function(req, file, cb)
{
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) =>
{
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png')
{
cb(null, true);
}
else
{
cb(null, false);
}
};
const upload = multer(
{
storage: storage,
limits:
{
fileSize: 1024 * 1024 * 50
},
fileFilter: fileFilter
});
router.post("/upload", upload.single('productImage'), (req, res, next) =>
{
if (!req.file)
return res.send('Please upload a file')
var tempPath = req.file.path
console.log(tempPath);
});
的package.json
{
"name": "api",
"version": "1.0.0",
"description": "testing version",
"main": "server.js",
"dependencies": {
"express": "^4.16.4",
"multer": "^1.3.0",
"nodemon": "^1.18.10",
},
"devDependencies": {},
"scripts": {
"test": "node server.js",
"start": "nodemon server.js"
},
"keywords": [
"api"
],
"author": "tteam",
"license": "ISC"
}
你的代码工作正常,我只需要将upload.single('productImage')
更改为upload.single('image')
,我没有遇到任何错误,如Please upload a file
,这是我的笔,它和你的一样,工作正常。
https://codepen.io/khanChacha/pen/rbJjYj
只有在您不选择任何文件或选择错误的文件类型时才会出现Please upload a file
我已更新您的代码并进行了一些更改,现在它的工作检查在这里:
错误:ENOENT:没有这样的文件或目录,打开'C:\ Users \ ttest \ Downloads \ Compressed \ uploads-master \ api \ routes \ uploads \ 2019-04-18T14:02:45.456Z55460132_25_63992_n(1).jpg'
我认为问题似乎与您存储上传文件的位置有关。您需要在存储文件之前检查upload/
的存在。
user.js的
const path = require('path');
const fs = require('fs-extra');
let UPLOAD_LOCATION = path.join(__dirname, 'uploads');
fs.mkdirsSync(UPLOAD_LOCATION); //create `uploads/` folder, if it doesn't exists
使用此位置存储上载文件
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, UPLOAD_LOCATION);
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
}
});
作为参考,您可以查看how to configure upload path in multer