【发布时间】:2020-02-24 00:16:51
【问题描述】:
我正在尝试使用 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)
}
Backend 使用内置的 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)
}
以及保存上传图片的代码(到谷歌云)
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)
同样,使用邮递员上传图像文件有效! 谢谢...
【问题讨论】:
-
请您指出这是哪一行:services/user.profile.service.js:53:47
-
@thinkwinwin 嗨,我编辑了问题以指向该代码
-
uploadedFile是未定义的,你在调用这个函数时传递了什么? -
@thinkwinwin 是的,上传图片邮递员按预期工作
标签: javascript angular http ionic-framework nestjs