S
S
sgawp2021-12-22 14:15:05
Angular
sgawp, 2021-12-22 14:15:05

How to get the url of the uploaded image?

This is the result that should get when uploading the image to the server.

{
    "url": "2021-12-22/d983d107f38ff22e244d45110913f8036e.webp",
    "name": "wallpape.webp"
}


How to get the url of the image to send to the form to save to the database?

service:

upload(image: File): Observable<ImgI> {
    const fd = new FormData();
    fd.append('image', image, image.name);
    return this._http.post<ImgI>(`${environment.url}/api/upload`, fd);
  }


ts:

image!: File;

form!: FormGroup;
user!: UserI;

imagePreview = '';

@ViewChild('input') input!: ElementRef;

ngOnInit(): void {
  this.initializeForm();
  this.userService
    .getPerson()
    .pipe(
      tap((user) => {
        this.form.get('email')?.setValue(user.email);
        this.form.get('image')?.setValue(this.imagePreview);
      })
    )
    .subscribe();
}

initializeForm(): void {
  this.form = this.fb.group({
    email: new FormControl('', Validators.required),
    image: new FormControl(''),
  });
}

onFileSelect(event: any) {
  const file = event.target.files[0];
  this.image = file;

  const reader = new FileReader();

  reader.onload = () => {
    this.imagePreview = reader.result as string;
  };

  reader.readAsDataURL(file);
  this.userService.upload(this.image).subscribe(
    () => {
      console.log(true)
    },
    (error) => {
      console.log(error.error.message);
    }
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Turnaviotov, 2021-12-22
@foxmuldercp

response from the server - {
"url": "2021-12-22/d983d107f38ff22e244d45110913f8036e.webp",
"name": "wallpape.webp"
} => json, respectively, the object, respectively, is taken by the obj[url] key or as is customary in Angular, do not know what "add-ons" you have there, unfortunately

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question