I'm trying to post an image using formdata to a nestJS powered backend and running into issues where the formdata is undefined when it reaches the backend. I tried uploading an image using postman and it worked as intended.
Here is my code for the Front end:
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);
})
And The Http Call
uploadUserPhoto(data: FormData){
return this.http.post(`${this.config.serverAddress}/api/user/photoUpload`, data)
}
The Backend uses the built in File Intreceptor to handle the image, 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)
}
And The code for saving the uploaded image (to google cloud)
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
});
And Here is the error that the file intrecptor throws:
[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)
And Again, uploading the image file using postman works. Thanks...
Ok, so I found out a solution for this. First of all, rather than getting a file url, get base64 from the ionic image picker. Then you create a blob from that base64 and append its content type. You can do this in any way you like but i did it via a node module, b64-to-blob ( https://www.npmjs.com/package/b64-to-blob ). After that, you create a form data from it and finally, http post.
Here's the code:
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);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.