![](/img/trans.png)
[英]How to upload canvas image through FormData/multipart with Jquery Ajax?
[英]Angular Upload image as multipart formdata (NestJS Backend)
我正在尝试使用 formdata 将图像发布到由 nestJS 驱动的后端,并遇到当 formdata 到达后端时未定义的问题。 我尝试使用 postman 上传图像,它按预期工作。
这是我的前端代码:
let blob = this.getBlob(results[i], ".png");
const file = new File([blob],name, {type:"image/png"});
let postData = new FormData();
postData.append('file', file);
this.httpService.uploadUserPhoto(postData)
.subscribe(res =>{
console.log(res)
}, error => {
console.log(error);
this.unknownError(error.name);
})
和 Http 通话
uploadUserPhoto(data: FormData){
return this.http.post(`${this.config.serverAddress}/api/user/photoUpload`, data)
}
后端使用内置的 File Intreceptor 来处理图像,文档: https://docs.nestjs.com/techniques/file-upload
@Post('photoUpload')
@UseGuards(AuthGuard)
@UseInterceptors(FileInterceptor('file'))
uploadFile(@User() user, @UploadedFile() file) {
return this.profileService.saveFile(user,file)
}
以及保存上传图片的代码(到谷歌云)
private fileUploader(userId: string, uploadedFile: any): Observable<any> {
return new Observable(observer => {
const fileName = `${userId}:${uniqId()}`;
const file = this.photoBucket.file(fileName);
const stream = file.createWriteStream({
metadata: {
contentType: uploadedFile.mimetype
},
resumable: false
});
这是文件 intrecptor 抛出的错误:
[Nest] 26603 - 10/28/2019, 5:38:34 PM [ExceptionsHandler] Cannot read property 'mimetype' of undefined +106042ms
TypeError: Cannot read property 'mimetype' of undefined
at Observable.rxjs_1.Observable.observer [as _subscribe] (PATH/dist/services/user.profile.service.js:53:47)
同样,使用 postman 上传图像文件是可行的。 谢谢...
好的,所以我找到了解决方案。 首先,与其获取文件 url,不如从离子图像选择器获取 base64。 然后从 base64 和 append 的内容类型创建一个 blob。 您可以以任何您喜欢的方式执行此操作,但我是通过节点模块 b64-to-blob ( https://www.npmjs.com/package/b64-to-blob ) 完成的。 之后,您从中创建一个表单数据,最后 http 发布。
这是代码:
if (this.user.photos.length < 5) {
this.imagePicker.getPictures({
maximumImagesCount: 1,
quality: 50,
outputType: 1
})
.then((results: string[]) => {
results.forEach(res => {
const contentType = 'image/png';
// @ts-ignore
let blob = b64toBlob(res, contentType);
let fd: FormData = new FormData();
fd.append('file', blob);
this.httpUpload(fd)
})
}, (err) => {
this.unknownError(err);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.