反应本机上传文件

时间:2017-05-19 10:53:01

标签: javascript reactjs react-native

是否可以使用FormData将文件(图像)上传到具有react-native的服务器? 试图像这样使用它:

const data = new FormData();
data.append('file', {uri: 'file://' + fileObject.uri, name: 'image.jpg', type: 'image/jpg;'});
const request = {
    method: method,
    mode: 'cors',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d',
    },
    body: data
  }
return fetch(`${API}/${url}`, request).then((response) => {
  return Promise.all([Promise.resolve(response), response.json()]);
})

对于Web FormData按预期工作,但对于react-native no。

尝试使用react-native-fetch-blob,但此处无法使用credentials(对我很重要),因此服务器发送unauthorized

希望你的帮助!

使用react-native-image-picker

进行图片选择

3 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,FormData为我工作。我也使用react-native-image-picker。

export const updateProfileData = (authToken, values) => {
  const data = new FormData();

  Object.keys(values).forEach(paramKey => {
    if (paramKey === 'birthday') {
      data.append(`profile[${paramKey}]`, moment(values[paramKey]).format('YYYY-M-D'));
    } else if (paramKey === 'avatar') {
      const photo = {
        uri: values[paramKey].uri,
        type: values[paramKey].type,
        name: values[paramKey].fileName,
      };
      data.append(`profile[${paramKey}]`, photo);
    } else {
      data.append(`profile[${paramKey}]`, values[paramKey]);
    }
  });

  return axios({
    method: 'PATCH',
    url: `${BASE_URL}/api/v1/current_profile`,
    headers: {
      'Auth-Token': authToken
    },
    data
  })
  .then((res) => {
    return res.data;
  });
};

photo使用来自图像选择器的数据构建。 示例中也有axios,但也应该使用fetchAPI。

答案 1 :(得分:0)

我使用POST方法和内容类型multipart/form-data实现了相同的功能(照片上传)。我还使用了react-native-image-picker

var ImagePicker = require('react-native-image-picker')


   function makeid(){
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for( var i=0; i < 5; i++ )
          text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;
    }

   function doUpload(image) {

        let API_URL = "API_URL"
        let fileURL = image
        let picName = makeid() + '.jpg'

        let data = new FormData()
        if (fileURL) {
          data.append('file', {uri: fileURL, name: picName, type: 'image/jpg'})
        }
        const config = {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d',
            'Content-Language': 'en'
          },
          body: data,
        }
        return fetch(API_URL, config)
          .then(response => response.json().then(photo => ({photo, response})))
          .then(({photo, response}) => {
            if(!response.ok) {
              return Promise.reject(photo)
            } else {
              profileImage = photo.url 
            }
          }).catch(err => {
            console.log(err.message)
          })    

      }

答案 2 :(得分:0)

我建议使用诸如react-uploady之类的库,该库将为您完成上载。在管理上传(很多文件,重试,取消等)方面有很多事情,在现实生活中的应用程序中,有很多边缘情况需要考虑。

import React, { useCallback, useContext } from "react";
import { View, Button } from "react-native";
import DocumentPicker from "react-native-document-picker/index";
import NativeUploady from "@rpldy/native-uploady";

const Upload = () => {

  const pickFile = useCallback(async () => {
      const res = await DocumentPicker.pick({
        type: [DocumentPicker.types.images],
      });

      uploadyContext.upload(res);
  }, [uploadyContext]);

    return <View>
               <Button title="Upload File" onPress={pickFile} />
          </View>;
};

const App = () => (<NativeUploady    
    grouped
    maxGroupSize={2}
    method="PUT"
    destination={{url: "https://my-server", headers: {"x-custom": "123"}}}>

    <Upload/>
    <RestOfMyApp/>
</NativeUploady>)