Unable to upload document / file to server using fetch / XMLHttpRequest in React-native

馋奶兔 提交于 2020-06-17 09:56:19

问题


I am trying to upload a document / image file to server. I tried using fetch (multipart), as well as XMLHttpRequest. The same thing is working fine with Postman.

1) using fetch multipart ---- getting network request failed

export async function upload(url, res, uploadedFileName) {

var data = {
  file1: {
    uri: res.uri,
    type: res.type,
    name: uploadedFileName,
  }
 };
  let options = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    method: 'POST'
  };

  options.body = new FormData();
  for (let key in data) {
    options.body.append(key, data[key]);
  }
  options.body.append('jsonKey', {CompanyName:"Test"});

  return new Promise(
    function (resolve, reject) {
      fetch(url, options)
      .then(
        function(response) {
          if (response.ok) {
             resolve(response.json());

          }
          else {
            console.log('response = '+JSON.stringify(response))

            reject(new Error(`Invalid response received - (${response.status}).`));
          }
        }
      )
      .catch(
        function(error) {
          var errorMsg = error.message;
          if(errorMsg === 'Network request failed') {
            errorMsg = 'Please check your network / internet connection.'
          }
          reject(new Error(`${errorMsg}`));
        }
      );
    }
  );

}

2) Using XMLHTTPRequest --- getting error 406

export async function uploadXHR(url, res, uploadedFileName) {

  var data = {
  file1: {
    uri: res.uri,
    type: res.type,
    name: uploadedFileName,
  }
 };
  var formData = new FormData();
  for (let key in data) {
    formData.append(key, data[key]);

  }
  formData.append('jsonKey', {CompanyName:"Test"});

  var xhr = new XMLHttpRequest();

  return new Promise(
    function (resolve, reject) {

      xhr.open("POST", url);

      xhr.onload = function () {
        if (this.status >= 200 && this.status < 300) {
          resolve(xhr.response);
        } else {
          // console.log('StatusText: '+xhr.statusText);
          reject({
            status: this.status,
            statusText: xhr.statusText
          });
        }
      };
      xhr.onerror = function () {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      };
      xhr.send();


    }
  );

}

NOTE: The fetch method works well, when no additional param is needed, except the file itself. But in case of sending additional param, it gets failed.

来源:https://stackoverflow.com/questions/62309620/unable-to-upload-document-file-to-server-using-fetch-xmlhttprequest-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!