php - How to upload image/file with formgroup value to API? -


how upload image , add form when service doing http.post? example product module needs name, price, coverimage. tried use many ways can internet, forum, etc. still got no clue issue.

i using model driven form , append when image selected , tried print out values of form before send api. attached image console.log result:

enter image description here

fyi: using api based on php laravel. tried image "$request->file('image');"

anybody can me case? thanks.

part 1. upload files api via formdata

in service file upload.service.ts need create function upload files via post method. here example function:

getuploadheaders() {     let headers = new headers({'accept': 'application/json'});     headers.delete('content-type');     return headers; }      addnewpost(newpost: formdata): observable<formdata> {     const endpoint = 'https://yourapiurl.com';      return this.http         .post(endpoint, newpost, { headers: this.getuploadheaders() })         .catch((e) => this.handleerror(e)); } 

and should create upload function in component, example upload.component.ts. here example upload function formdata.

filetoupload: file = null;  constructor(private uploadservice: uploadservice) { }  handlefileinput(files: filelist) {   this.filetoupload = files.item(0); }   savefiletoapi() {   const saveform: formdata = new formdata();         if (this.filetoupload) {     // if need/want append other fields api endpoint     saveform.append('name', this.name);     saveform.append('link', this.link);     saveform.append('description', this.description);     // if have append number     saveform.append('age', this.age.tostring());     // append image     saveform.append('filefieldnameonyourapi', this.filetoupload, this.filetoupload.name);   }    this.uploadservice.addnewpost(saveform).subscribe(() => {     console.log('upload success!');   }, error => {     console.log('upload failed!');   }); } 

in savefiletoapi-function can append other fields of form. beware should convert number fields string. here can read more usage if formdata objects.

for uploading file via formdata need 3 parameters: propertyname on api endpoint, file , name of file. , in upload.component.html need have form one:

<form (ngsubmit)="onsubmit()">          <label for="filefield">chose file upload</label>     <input type="file"            id="filefield"            name="filefield"            (change)="handlefileinput($event.target.files)">     <button type="submit">speichern</button> </form> 

for more detail of formdata read this , more information formdata.append() read this.

part 2. uploaded image api

you should set responsetype: responsecontenttype.blob in get-request settings, because can image blob , convert later da base64-encoded source. code above not good. if correctly, create separate service images api. beacuse ism't call http-request in components.

here working example:

create image.service.ts or use upload.service.ts part 1 (maybe can give service name) , put following code:

    getimage(imageurl: string): observable<file> {         return this.http             .get(imageurl, { responsetype: responsecontenttype.blob })             .map((res: response) => res.blob());     } 

now need create function in image.component.ts image , show in html.

for creating image blob need use javascript's filereader. here function creates new filereader , listen filereader's load-event. result function returns base64-encoded image, can use in img src-attribute:

imagetoshow: any;  createimagefromblob(image: blob) {        let reader = new filereader();        reader.addeventlistener("load", () => {           this.imagetoshow = reader.result;        }, false);         if (image) {           reader.readasdataurl(image);        } } 

now should use created imageservice image api. should subscribe data , give data createimagefromblob-function. here example function:

getimagefromservice() {       this.isimageloading = true;       this.imageservice.getimage(yourimageurl).subscribe(data => {         this.createimagefromblob(data);         this.isimageloading = false;       }, error => {         this.isimageloading = false;         console.log(error);       }); } 

now can use imagetoshow-variable in html template this:

<img [src]="imagetoshow"      alt="place image title"      *ngif="!isimageloading; else noimagefound"> <ng-template #noimagefound>      <img src="fallbackimage.png" alt="fallbackimage"> </ng-template> 

i hope description clear understand , can use in project.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -