1

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

 <input type="file" accept="image/png, image/jpeg" class="form-control upload-btn" formControlName="imageUpload" placeholder="Upload Images" (change)="uploadImage($event)"  required>

.ts file

 uploadImage(event: any) {
if (event.target.files && event.target.files[0]) {
  const uploadImage=event.target.files[0];

  const fileObject = {
    userId: this.userId,
    bucketName: 'Test123',
    image: uploadImage
  };

  this.userService.uploadImage(fileObject).subscribe(data=>{
  },err=>{
    console.log("error occured")
  }
  )
}

}

.service file

uploadImage(fileObject: any){
return this.http.post('http://localhost:1337' + 'upload-image' , fileObject);

}

No any error occurs on the backend side. It worked fine with Postman. Im not sure about the .ts file.

13
  • What's the error you are seeing in frontend/browser or developer tools Commented Mar 29, 2022 at 4:32
  • can you share the which url you are using in the postman to upload can you post here the url Commented Mar 29, 2022 at 4:33
  • Hi @chintuyadavsara, error is it will never go inside this.userService.uploadImage(fileObject).subscribe(data=>{ } this one. Therefore image didn't add the bucket Commented Mar 29, 2022 at 4:36
  • Hi @ManektechKnowledgeBase, I used http://localhost:1337/upload-image this url which is same as in the service file. Commented Mar 29, 2022 at 4:37
  • 1
    Here is the example which shows how to use FormData as suggested by @PrasenjeetSymon Commented Mar 29, 2022 at 7:07

1 Answer 1

1

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:

<input type="file" name="file" id="file" (change)="onFileChanged($event)" />

and in the component:

public files: any[];

contructor() { this.files = []; }

onFileChanged(event: any) {
  this.files = event.target.files;
}

onUpload() {
  const formData = new FormData();
  for (const file of this.files) {
      formData.append(name, file, file.name);
  }
  this.http.post('url', formData).subscribe(x => ....);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.