使用Angular 5 Nodejs和Multer 我正在尝试上传文件,所以首先我试图将文件放到某个目录,然后该路径必须插入到数据库, 所以首先我创建了表单
<input type="file" (change)="onFileSelected($event)">
<button type="button" (click)="onUpload()">Upload</button>
之后我在我的.ts文件中有了这些功能
onFileSelected(event){
this.selectedFile = event.target.files[0];
}
onUpload(){
var fd = new FormData();
fd.append('productImage', this.selectedFile, this.selectedFile.name);
this.httpClient.post('http://localhost:3000/uploadImage/1', fd )
.subscribe(res => {
console.log(res);
});
}
我的节点休息呼叫如下
app.post('/uploadImage/:id', upload.single("productImage") ,(request, result) => {
result.send(request.file);
result.send(request.params.id);
result.send("Done");
});
我感到困惑的部分是因为我在节点侧设置标题如何从前端删除它以避免以下错误,该错误表示在发送时无法设置标题
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:767:10)
at ServerResponse.contentType (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:595:15)
at ServerResponse.send (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:145:14)
at app.post (D:\Projects\Craiglist\api\index.js:41:12)
at Layer.handle [as handle_request] (D:\Projects\Craiglist\api\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Projects\Craiglist\api\node_modules\express\lib\router\route.js:137:13)
at Array.<anonymous> (D:\Projects\Craiglist\api\node_modules\multer\lib\make-middleware.js:53:37)
at listener (D:\Projects\Craiglist\api\node_modules\on-finished\index.js:169:15)
答案 0 :(得分:1)
你可以在每个路线中只使用一次result.send函数。 你的代码应该是这样的:
app.post('/uploadImage/:id', upload.single("productImage") ,(request, result) => {
finalResult = {
requestFile: request.file,
requestParams: request.params.id,
message: "Done!"
};
result.send(finalResult);
});