简体   繁体   中英

i am trying to upload a file using fetch API and formData - angular material

I am trying to upload an image and send the formData to the backend.

I am using formData.append to append the uploadedFile and fetchAPI to send the formData.

My Input looks like below

<input style="display:none" type="file"
                               (change)="fileChange($event)"
                               #fileInput>
fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    console.log('formData', formData);
    this.handleUpload(formData);
    }
  }
handleUpload(formData) {
    const url = `/upload?`;
    let result;
    const req = new Request(proxyurl + url,
      {
        method: 'POST',
        headers: {
          'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
    },
        body: formData
      });
    fetch(req)
      .then(response => response.text())
      .then(() => {
        if (result.data) {
          console.log('response ', result.data);
        } else {
          console.log('request failed');
        }
      })
      .catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?'));
  }

When i hit the service, i get Status Code: 422 Unprocessable Entity with below response

{"error":{"message":"?exception.illegalargument?"}}

Request Payload is as below

------WebKitFormBoundary8E02ll3T0mo433bu
Content-Disposition: form-data; name="uploadFile"; filename="Screen Shot 2019-10-04 at 10.49.34 AM.png"
Content-Type: image/png


------WebKitFormBoundary8E02ll3T0mo433bu--

Please help me on how to get this working.

I got it working by doing the below:

removed the headers and checked if server is expecting uploadFile.

working code below:

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
      formData.append('uploadedFile', file, file.name);
      this.handleUpload(formData);
    }
  }

  handleUpload(formData) {
    const url = `/upload?`;
    let result;
    const req = new Request(url,
      {
        method: 'POST',
        headers: {},
        body: formData
      });
    fetch(req)
      .then(response => response.text())
      .then(() => {
        if (result.data) {
          console.log('response data ', result.data);
        } else {
          console.log('request failed');
        }
      })
      .catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?'));
  }

It worked when i do not add any headers.

 handleUpload(formData) {
     const url = `/upload`;
     const proxyurl = 'https://cors-anywhere-proxy.herokuapp.com/';
     let result;
     const req = new Request(proxyurl + url,
       {
         method: 'POST',
         headers: {},
         body: formData
       });
     fetch(req)
       .then(response => response.text())
       .then(() => {
         if (result.data) {
           console.log('result.data', result.data);
         } else {
           console.log('request failed');
         }
       })
       .catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?'));
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM