angular - 如何修复未知错误(空 FormData 文件)上传图像文件
问题描述
如果有人可以帮我修复以下代码,它发送空的“FormData object to
http/post”,我将不胜感激:
我在网上看了几天,但没有一个所谓的修复工作。
app.component.html
<input type="file" (change)="onSelectFile($event)" >
<button (click)="uploadFiles()">Upload</button>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
selectedFile: File;
constructor(private http: HttpClient) { }
ngOnInit() {
}
onSelectFile(event) {
this.selectedFile = <File>event.target.files[0];
console.log("File name: " + this.selectedFile.name);
}
uploadFiles() {
let fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.name);
console.log("Uploading: " + JSON.stringify(this.selectedFile.name));
try {
this.http.post("http://localhost:3000/selection/test-photo",fd)
.subscribe(
(res) => {
console.log("Successful response: " + res)},
(err) => {
console.log("Subscribe error: " + JSON.stringify(err))}
);
}
catch(e) {
console.log("Caught error: " + e);
}
}
}
关于selection_controller.js
Express 中的后端路由,我现在要做的就是记录http.post
请求:
exports.selection_test_photo = [
(req,res,next) => {
console.log("Posting . . . ");
console.log("Photos: " + util.inspect(req.body));
res.json(req.body);
}
];
这是运行后的客户端屏幕截图:
和服务器端日志记录:
解决方案
这是解决方案。根据@Shashank Vivek 的建议,主要的是我需要multer
在后端使用:
前端(角度):
uploadFiles() {
let fd = new FormData();
fd.append('image', this.selectedFile);
fd.append('timeStamp', Date.now().toString());
try {
this.http.post("http://localhost:3000/selection/test-photo",fd)
// this.http.post("http://localhost:3000/selection/test-photo",this.selectedFile)
.subscribe(
(res) => {
console.log("Successful result: " + JSON.stringify(res))},
(err) => {
console.log("Subscribe error: " + JSON.stringify(err))}
);
}
catch(e) {
console.log("Caught error: " + e);
}
}
后端数据模型(Express):
var PhotoSchema = new Schema (
{
timeStamp: {type: Object},
photo: {data: Buffer, contentType: String}
}
)
app.js
var multer = require('multer');
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename;
},
}
).single('image'));
照片上传路由回调函数:
var fs= require('fs');
exports.selection_test_photo = [
(req,res,next) => {
const photo = new Photo();
photo.photo.data = fs.readFileSync(req.file.path);
photo.photo.contentType = 'image/png';
photo.timeStamp = {"value": req.body.timeStamp};
photo.save(function(err){
if (err) {return next(err)};
res.json({"foo": "bar"});
});
},
];
推荐阅读
- c# - 如何在 ASP.NET Core 中路由以删除错误 404 Not found
- string - 如何知道这个文件的编码?
- elixir - 如何通过 Ecto Multi 从先前插入的表键中检索 id
- ios - 如何从标签栏控制器更改标签栏项目
- python - Python PLY Parser - 将矩阵解析为列表列表
- python - QApplication 模块的 PyQt5 问题
- asp.net-core - 实体框架核心 2.1。使用大量子对象更新对象的正确方法
- c++ - C++:矩阵的运算符重载
- excel - Nesting ParamArrays when declaring Excel VBA functions like SUMIFS?
- flutter - 检查约束并相应地返回正文