我正在尝试将使用formdata的图像发布到一个由nestJS驱动的后端,并遇到一个问题,即到达后端时formdata不确定。我尝试使用邮递员上传图片,并且按预期工作。
这是我的前端代码:
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处理图像Docs: 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)
}
以及用于将上传的图片保存到Google云的代码
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)
同样,使用邮递员上传图像文件也可以! 谢谢...
答案 0 :(得分:0)
好的,所以我找到了解决方案。首先,从离子图像选择器获取base64,而不是获取文件url。然后,您从该base64创建一个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);
});
}