我能够使用multer成功地将图像存储在本地磁盘存储中,但是在使用GET方法时,它会引发“无法获取/ uploads / image-1547436792386”错误。我在下面提供了我的image-upload.js代码:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
});
const upload = multer({ storage: storage });
module.exports = upload;
Service.ts:
const imageUpload = require('../services/image-upload');
const singleUpload = imageUpload.single('image');
module.exports = function(app) {
app.post('/api/image-upload', auth.jwtRefreshToken, imageUploadRoute);
};
function imageUploadRoute(req, res) {
const userId = req.userId;
if (typeof userId !== 'string') {
return res.status(422).json({message: 'Error in UserId'});
}
singleUpload(req, res, function(err) {
if (err) {
return res.status(422).send({errors: [{title: 'Image Upload error', detail: err.message}]});
}
User.findOne({_id: userId})
.then((user) => {
console.log(req.file);
user.profileImage = req.file.path;
return user.save()
.then(() => {
return res.status(200).send({message: 'Image Uploaded Successfully'});
})
.catch(() => {
return res.status(500).send({message: 'Error in uploading image'});
});
})
.catch(() => {
return res.status(500).send({message: 'UserId not found'});
});
});
}
答案 0 :(得分:0)
您的GET API的实现在哪里?无论如何,下面的代码可以帮助我下载文件。请尝试这个。
app.get("/download/:name(*)", function (req, res, next) {
var file = req.params.name;
var path = '/yourFileLocation' + '/' + file;
res.download(path, file, function (err) {
if (err) {
res.status(500).send({ "error": 'Unexpected error occured.' });
} else {
res.send({ "message": 'success' });
}
});
});