How to upload file to server using react-native

后端 未结 7 1353
渐次进展
渐次进展 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: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
        });
    })
    
    

提交回复
热议问题