How to upload file to server using react-native

后端 未结 7 1319
渐次进展
渐次进展 2020-12-12 20:36

I am developing a app where i need to upload an image to the server. Based on the image i get a response which i need to render?.

Can you please help me how to uploa

相关标签:
7条回答
  • 2020-12-12 21:11

    A couple of potential alternatives are available. Firstly, you could use the XHR polyfill:

    http://facebook.github.io/react-native/docs/network.html

    Secondly, just ask the question: how would I upload a file in Obj-C? Answer that and then you could just implement a native module to call it from JavaScript.

    There's some further discussion on all of this on this Github issue.

    0 讨论(0)
  • 2020-12-12 21:17

    Tom's answer didn't work for me. So I implemented a native FilePickerModule which helps me choose the file and then use the remobile's react-native-file-transfer package to upload it. FilePickerModule returns the path of the selected file (FileURL) which is used by react-native-file-transfer to upload it. Here's the code:

    var FileTransfer = require('@remobile/react-native-file-transfer');
    var FilePickerModule = NativeModules.FilePickerModule;
    
          var that = this;
          var fileTransfer = new FileTransfer();
          FilePickerModule.chooseFile()
          .then(function(fileURL){
            var options = {};
            options.fileKey = 'file';
            options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
            options.mimeType = 'text/plain';
            var headers = {
              'X-XSRF-TOKEN':that.state.token
            };
            options.headers = headers;
            var url = "Set the URL here" ;
            fileTransfer.upload(fileURL, encodeURI(url),(result)=>
            {
                  console.log(result);
              }, (error)=>{
                  console.log(error);
              }, options);
         })
    
    0 讨论(0)
  • 2020-12-12 21:24

    I wrote something like that. Check out https://github.com/kamilkp/react-native-file-transfer

    0 讨论(0)
  • 2020-12-12 21:25

    I have been struggling to upload images recently on react-native. I didn't seem to get the images uploaded. This is actually because i was using the react-native-debugger and network inspect on while sending the requests. Immediately i switch off network inspect, the request were successful and the files uploaded.

    I am using the example from this answer above it works for me.

    This article on github about the limitations of network inspect feature may clear things for you.

    0 讨论(0)
  • 2020-12-12 21:27

    My solution is using fetch API and FormData.

    Tested on Android.

    const file = {
      uri,             // e.g. 'file:///path/to/file/image123.jpg'
      name,            // e.g. 'image123.jpg',
      type             // e.g. 'image/jpg'
    }
    
    const body = new FormData()
    body.append('file', file)
    
    fetch(url, {
      method: 'POST',
      body
    })
    
    0 讨论(0)
  • 2020-12-12 21:27

    Just to build on the answer by Dev1, this is a good way to upload files from react native if you also want to show upload progress. It's pure JS, so this would actually work on any Javascript file.

    (Note that in step #4 you have to replace the variables inside the strings with the type and file endings. That said, you could just take those fields out.)

    Here's a gist I made on Github: https://gist.github.com/nandorojo/c641c176a053a9ab43462c6da1553a1b

    1. for uploading one file:

    
    // 1. initialize request
    const xhr = new XMLHttpRequest();
    // 2. open request
    xhr.open('POST', uploadUrl);
    // 3. set up callback for request
    xhr.onload = () => {
        const response = JSON.parse(xhr.response);
    
        console.log(response);
        // ... do something with the successful response
    };
    // 4. catch for request error
    xhr.onerror = e => {
        console.log(e, 'upload failed');
    };
    // 4. catch for request timeout
    xhr.ontimeout = e => {
        console.log(e, 'cloudinary timeout');
    };
    // 4. create formData to upload
    const formData = new FormData();
    
    formData.append('file', {
        uri: 'some-file-path',          // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
        type: `${type}/${fileEnding}`,  // example: image/jpg
        name: `upload.${fileEnding}`    // example: upload.jpg
    });
    // 6. upload the request
    xhr.send(formData);
    // 7. track upload progress
    if (xhr.upload) {
        // track the upload progress
        xhr.upload.onprogress = ({ total, loaded }) => {
            const uploadProgress = (loaded / total);
            console.log(uploadProgress);
        };
    }
    
    
    

    2. uploading multiple files Assuming you have an array of files you want to upload, you'd just change #4 from the code above to look like this:

    
    // 4. create formData to upload
    const arrayOfFilesToUpload = [
        // ...
    ];
    const formData = new FormData();
    
    arrayOfFilesToUpload.forEach(file => {
        formData.append('file', {
            uri: file.uri,                  // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
            type: `${type}/${fileEnding}`,  // example: image/jpg
            name: `upload.${fileEnding}`    // example: upload.jpg
        });
    })
    
    
    0 讨论(0)
提交回复
热议问题