【发布时间】:2021-06-01 16:27:22
【问题描述】:
我无法将通过 VueJS 前端发送的上传文件保存到 Node + Express 后端。数据通过多部分表单数据从前端发送,因此所有元数据和文件本身都附加在请求正文中。下面是后端的路由器
import {submitFlag} from '../some/dir/controller.js'
const router = express.Router();
const app = express();
app.use(express.json());
router.post('/submit-flag', [], submitFlag)
以及处理来自路由器的 API 请求的后端控制器
import multer from 'multer';
const evidencePathSave = '../uploads/flagEvidence'
export const submitFlag = async (req, res) => {
const evidenceStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, evidencePathSave)
},
filename: function (req, file, cb) {
cb(null, req.body.flagEvidence.name);
}
})
const uploadEvidence = multer({
storage: evidenceStorage,
fileFilter: (req, res, cb) => {
const filetypes = /pdf|doc|docx|txt/;
const mimetype = filetypes.test(req.body.flagEvidence.type);
const extname = filetypes.test(path.extname(req.body.flagEvidence.name));
// if mimetype && extname are true, then no error
if(mimetype && extname){
return cb(null, true);
}
// if mimetype or extname false, give an error of compatibilty
return cb("The uploaded file, isn't compatible");
}
}).fields([
{name: 'flagEvidence', maxCount: 1}
]);
uploadEvidence(req, res, function(err) {
if (err) {
console.log(err)
res.status(500).send("Error in Saving");
}
})
res.status(200)
}
该函数不返回任何错误或状态 500 消息,但是在检查本地存储时,似乎在任何地方都找不到该文件。删除文件过滤功能似乎不起作用。
前端Vue功能如下
submitFlag(event) {
this.flagEvidence = event.target.files[0]
var formData = new FormData()
formData.append('flagSubject', this.flagSubject)
formData.append('flagWriteup', this.flagWriteup)
formData.append('flagEvidence', this.flagEvidence)
formData.append('userID', this.user._id)
formData.append('username', this.user.username)
formData.append('publicationID', this.publicationID)
formData.append('filename', this.flagEvidence.name)
axios({
method: "POST",
url: serverSide.submitFlag,
data: formData,
headers: {"Content-type": "multipart/form-data"}
})
.then((res) => {
this.$router.push({name: "news", query:{id: this.publicationID}})
})
.catch(function (error) {
console.error(error.response);
});
}
【问题讨论】:
标签: node.js vue.js express multer