Search code examples
node.jsaxiosmultipartform-dataform-data

Creating form-data from file object in nodejs


I want to call third-party API (to upload an image) on the node side that expects a File type object on key file.

The front end is in Angular so the flow is

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

Node API layer using giuseppe

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

Facade Layer

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

At facade layer it is showing

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

The __resourceInfo have correct info at facade layer, but creating FormData from it is the cause of the error?


Solution

  • This is how I have handled this at the facade layer, instead of this

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

    I created the file field using Buffer.from

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

    There could be another solution, but this solved my problem.