I was trying to upload an image using Angular to a google storage bucket. And everything is working fine with Postman. But I’m stuck with angular typescript. Can anyone suggest to me a way to do this?
.html file
JavaScript
x
2
1
<input type="file" accept="image/png, image/jpeg" class="form-control upload-btn" formControlName="imageUpload" placeholder="Upload Images" (change)="uploadImage($event)" required>
2
.ts file
JavaScript
1
17
17
1
uploadImage(event: any) {
2
if (event.target.files && event.target.files[0]) {
3
const uploadImage=event.target.files[0];
4
5
const fileObject = {
6
userId: this.userId,
7
bucketName: 'Test123',
8
image: uploadImage
9
};
10
11
this.userService.uploadImage(fileObject).subscribe(data=>{
12
},err=>{
13
console.log("error occured")
14
}
15
)
16
}
17
}
.service file
JavaScript
1
3
1
uploadImage(fileObject: any){
2
return this.http.post('http://localhost:1337' + 'upload-image' , fileObject);
3
}
No any error occurs on the backend side. It worked fine with Postman. Im not sure about the .ts file.
Advertisement
Answer
As suggested by @PrasenjeetSymon using FormData will help to upload images in Angular.
Here is the similar thread which demonstrate how to use FormData
You can use the tag from HTML:
JavaScript121<input type="file" name="file" id="file" (change)="onFileChanged($event)" />
2
and in the component:
JavaScript116161public files: any[];
2
3contructor() { this.files = []; }
4
5onFileChanged(event: any) {
6this.files = event.target.files;
7}
8
9onUpload() {
10const formData = new FormData();
11for (const file of this.files) {
12formData.append(name, file, file.name);
13}
14this.http.post('url', formData).subscribe(x => .);
15}
16