Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not uploading in server ionic3

I have a scenario where I am uploading a image file from my local drive (type jpeg or png) to an API endpoint using ionic. Here is my code below :

fileupload.html -->

//---------------------------------------------------
  <ion-item>
    <ion-input type="file" accept="image/*" (change)="changeListener($event)"> </ion-input>
  </ion-item>

fileupload.ts -->

changeListener($event):void{
    this.file=$event.target.files[0];
    console.log(this.file);
    console.log("upload...");
    let regData={"file":this.file};
    console.log("REGDATAA"+JSON.stringify(regData));
    this.jira.postAttachment("PM-3",regData).subscribe(dataa=>{
      console.log(dataa);
    });
  }

provider.ts -->

public postAttachment(key,data):Observable<any>{
    console.log(JSON.stringify(data))
    return this.http.post(this.api+'/issue/'+key+'/attachments',JSON.stringify(data),{
      headers: new HttpHeaders()
        .append('Authorization', `Basic ${this.auth.getAuthString()}`)
        .append('Content-Type','multipart/form-data';boundary="-------xe3rtyhrfds")
        .append("X-Atlassian-Token", "no-check")
        .append("User-Agent", "xx")
    });
  } 

every time I send the file it doesn't take the path and sends an empty response, here is the error below.

 //----------------------------------------------------
  [object File]: {lastModifiedDate: [date] Fri Sep 21 2018 17:42:46 GMT+0530 (India Standard Time), name: "download.jpg", size: 5056, type: "image/jpeg", webkitRelativePath: ""}

 upload...
ion-dev.js (157,11)

 REGDATAA{"file":{}}
ion-dev.js (157,11)

 {"file":{}}
ion-dev.js (157,11)

ERROR [object Object]

I have resolved CORS issue and there is no problem with the same.

When I send the same response using postman it succeeds here is what I send in Postman.

Form-data 
key - "file" (type file) value - "/path/to/my/file"

Headers
Content-type - application/json
x-attlassian token - no-check

Can somebody advice what is going wrong here.

like image 872
Alex Avatar asked Sep 25 '18 07:09

Alex


1 Answers

Use FormData to upload file.

fileupload.ts

    changeListener(event) {

      const fd = new FormData();
      this.file = event.target.files[0];
      fd.append('file', this.file, this.file.name);
      this.jira.postAttachment("PM-3",fd)
        .subscribe(data => {

          console.log(data);
    });
  }

provider.ts

  postAttachment(key, fd): Observable<any> {

  const httpOptions = {
    headers: new HttpHeaders(
      { 'Content-Type': 'multipart/form-data' },
      { 'Authorization': `Basic ${this.auth.getAuthString()}` })
      };
  return this.http.post(this.api+'/issue/'+key+'/attachments', fd, httpOptions);

  }
like image 88
Sudarshana Dayananda Avatar answered Oct 25 '22 16:10

Sudarshana Dayananda