问题描述
我正在尝试构建一个 API,它将接收图像,因此为此使用了 multer,我成功上传了图像,但它以某种奇怪的格式保存,而不是我试图保存的实际格式.相关代码我会贴在这里.
I am trying to build an API which will take in image so used multer for that purpose, I am getting a success for uploading an image but it saves in some weird format not the actual format I tried to save.I ll post the related code here.
在 app.js 中
const multer = require('multer');
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "http://localhost:3001");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.use(express.static('../client'));
app.use(bodyParser.json());
app.use(multer({dest:'./angular-src/src/assets/'}).single('file'));
app.use(express.static(path.join(__dirname,'public')));
在 API 文件中
const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({ //multers disk storage settings
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({
storage: storage
}).single('file');
router.post('/upload',function (req,res) {
upload(req,res,function (err) {
if (err){
res.json({success:false});
return;
}else{
// console.log(req.files[0].originalname);
res.json({success: true, filename: req.file});
}
});
});
module.exports = router;
存储的图像看起来像这样
The stored image looks like this
其中包含字母数字字符的第二个.
The second one which has alpha numeric characters in it.
图像数据是这样的
{
"_type": "Project",
"_id": "AAAAAAFF+h6SjaM2Hec=",
"name": "Untitled",
"ownedElements": [
{
"_type": "UMLModel",
"_id": "AAAAAAFF+qBWK6M3Z8Y=",
"_parent": {
"$ref": "AAAAAAFF+h6SjaM2Hec="
},
"name": "Model",
"ownedElements": [
{
"_type": "UMLClassDiagram",
"_id": "AAAAAAFF+qBtyKM79qY=",
"_parent": {
"$ref": "AAAAAAFF+qBWK6M3Z8Y="
},
"name": "Main",
"visible": true,
"defaultDiagram": true
},
这就是我给邮递员打电话的方式
This is how I am making a call from postman
推荐答案
这个问题已经解决了,对于有类似问题的人.对我有用的是做
This issue has been solved, for those who has similar kind off issue. What worked for me was doing
app.use(multer({dest:'./angular-src/src/assets/'}).single('file'));
在 API 类本身中.
in the API class itself.
这篇关于Expressjs使用multer上传图像以奇怪的格式保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!