从nodejs中的文件对象创建表单数据

时间:2019-02-27 06:48:40

标签: node.js axios multipartform-data form-data

我想在期望键File上有file类型对象的节点侧调用第三方API(上传图像)。

前端在Angular中,所以流程是

.ts

const _file: File = __userAvatar.files[0];
const _userAvatarInfo = { userId: this.user.id, avatar: _file };
            this.userService.updateUserAvatar(_userAvatarInfo).subscribe(

UserService.ts

const _formData = new FormData();
_formData.append("avatar", _userAvatarInfo.avatar);
_formData.append("userId", _userAvatarInfo.userId);

return this.http.post(`${this.context}/userservice/user/updateuseravatar`, _formData);

使用giuseppe

的节点API层
@Post("/user/updateuseravatar")
updateUserAvatar(@Req() req: any): Promise<any> {
      return TrusteeFacade.uploadResource({ resourceId: "some_id", resource: req.files.avatar });
}

门面层

static uploadResource(__resourceInfo: any): Promise<any> {
    const _resourceData = new FormData();
    _resourceData.append("mimetype", "image/png");
    _resourceData.append("file", __resourceInfo.resource);

    // this will not get printed    
    console.log("From**************", __resourceInfo.resource);
    return axios({
        method: "post",
        url: `${process.env.REST_URL}/resources/${__resourceInfo.resourceId}`,
            headers: _resourceData.getHeaders(),
            data: _resourceData
    });
}

在外墙层正在显示

TypeError: source.on is not a function
    at Function.DelayedStream.create (D:\QPP Workspace\ContentPlatform\webapplications\application-services\node_modules\delayed-stream\lib\delayed_stream.js:33:10)
    at FormData.CombinedStream.append (D:\QPP Workspace\ContentPlatform\webapplications\application-services\node_modules\combined-stream\lib\combined_stream.js:44:37)
    at FormData.append (D:\QPP Workspace\ContentPlatform\webapplications\application-services\node_modules\form-data\lib\form_data.js:74:3)
    at Function.uploadResource (D:\QPP Workspace\ContentPlatform\webapplications\application-services\.bin\facade\trustee-facade.js:221:23)
    at trustee_facade_1.TrusteeFacade.getFileResourceId.then (D:\QPP Workspace\ContentPlatform\webapplications\application-services\.bin\api\user-service.js:118:51)
    at propagateAslWrapper (D:\QPP Workspace\ContentPlatform\webapplications\application-services\node_modules\async-l

__resourceInfo在外观层上的信息正确,但是从中创建FormData是错误的原因吗?

1 个答案:

答案 0 :(得分:0)

这就是我在外墙层处理此问题的方法,而不是

_resourceData.append("file", __resourceInfo.resource);

我使用file创建了Buffer.from字段

_resourceData.append("file", Buffer.from(__resourceInfo.resource.data), { filename: __resourceInfo.resource.name });

可能还有其他解决方案,但这解决了我的问题。