【问题标题】:Angular Upload image as multipart formdata (NestJS Backend)Angular 将图像上传为多部分表单数据(NestJS 后端)
【发布时间】: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


【解决方案1】:

好的,所以我找到了解决方案。首先,不是获取文件 url,而是从 ionic 图像选择器获取 base64。然后,您从该 base64 创建一个 blob 并附加其内容类型。你可以用任何你喜欢的方式做到这一点,但我是通过节点模块 b64-to-blob (https://www.npmjs.com/package/b64-to-blob) 做到的。之后,您从它创建一个表单数据,最后,http post。

代码如下:

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);
                });

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 2016-11-03
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2020-04-08
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多