10

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.

Alex
  • 197
  • 2
  • 19

4 Answers4

4

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);

  }
Sudarshana Dayananda
  • 5,311
  • 2
  • 15
  • 38
1

Your have to change the content type from application/json to multipart/form-data. You are sending an image, not a json-file.

QuickSort
  • 158
  • 1
  • 12
1

Best way is to encode your image to base64 and send it. Everything depends about what your server needs.

or you can try this.

const body = file;

    const headers = new Headers({'Content-Type': 'image/jpg'});
    return this.http.post(this.api+'/issue/'+key+'/attachments, body, {headers: headers}). ...
Kilomat
  • 125
  • 9
  • encoding my image to base-64 is fine but what I am worried about is if the resolution if picture is high then base64 string would be too long – Alex Sep 25 '18 at 13:30
  • Also using the 2nd option you mentioned says that Content-type image/jpeg is not in a valid format so I switched to multipart/form-data – Alex Sep 25 '18 at 13:32
  • humm. if you cannot use base64 maybe you should use Filestransfert https://ionicframework.com/docs/native/file-transfer/ – Kilomat Sep 26 '18 at 14:42
  • File transfer has been deprecated – Alex Sep 26 '18 at 17:21
1

For an issue on AngularJS what ended up working is (might a similar aproach help you too) :

  • make a hidden input de type file

  • set it's value in the changeListener function

  • make the file send from there afterwards

    • The reason being some built in propertie of the file input let's its value be recognised as File/Blob instead of the path many "complex" components use.
  • Also send it as multipart file as mentioned before.

T.S.
  • 29
  • 5