使用反复原生的formdata上传图像

时间:2016-11-23 09:49:21

标签: reactjs react-native

如何使用react-native的fetch api将文件上传到服务器 需要实现与此类似的东西 -

------WebKitFormBoundaryRAxza9ew2ADaYHn5
Content-Disposition: form-data; name="file"; filename="66154520.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryRAxza9ew2ADaYHn5--

3 个答案:

答案 0 :(得分:5)

你没有展示任何类型的代码,但理论上......

您应该将网址从ImagePickerCameraRoll(看起来与file:///storage/emulated/0/Pictures/shj15791-4v61-67g6-z1b6-v8451z956j5k.jpg类似)传递给formData,然后将其与请求一起传递:

const form = new FormData();

form.append('image', {
  uri: "file:///...",
  type: 'image/jpg',
  name: 'image.jpg',
});

fetch('https://example.com/api/upload', {
  method: 'POST',
  body: form
});

答案 1 :(得分:0)

这是您如何在 react-native 中将图像或文件上传到服务器:

  const data = await this.camera.takePictureAsync(options);
  URL = data.uri

  const form = new FormData();
  form.append('image', {
    name: 'image',
    type: 'image/jpeg',
    uri: URL,
  });
  axios
    .post(`url`, form)
    .then(function (response) {
        console.log('kkkkkkkkkkkk', response.data);
    })
    .catch(function (error) {
      console.log('errrrrrrrrrrrr', error);
    });

答案 2 :(得分:-1)

这对我有用。在Android和iOS上针对相机和图库进行了测试

const os = Platform.OS

    let data = new FormData();
    if (os == 'android') {
      const fileName = new Date().getTime() + getExtention(mime);
      let fileInfo = '';
      await RNFS.copyFile(uri, RNFS.CachesDirectoryPath + '/' + fileName).catch(e => {
        fileInfo = undefined;
      });
      
      if (!fileInfo) {
        fileDetail = await RNFS
          .stat(RNFS.CachesDirectoryPath + '/' + fileName)
          .catch(e => {});
        data.append('file', {
          name: getFilename(fileDetail.path),
          type: payload.file.type,
          uri: 'file://' + fileDetail.path,
        });
      }

    } else {
      let  localPath= uri;
      if (!localPath.includes('private')) {
        localPath = localPath.replace('/var', '/private/var');
      }
      data.append('file', {
        name: getFilename(localPath),
        type: mime,
        uri: localPath.replace('file://', ''),
      });
    }

 export const getFilename = url => {
      return url.substr(url.lastIndexOf('/') + 1);
    };
    
export const getExtention = mime => {
  switch (mime) {
    case 'application/pdf':
      return '.pdf';
    case 'image/jpeg':
      return '.jpg';
    case 'image/jpg':
      return '.jpg';
    case 'image/png':
      return '.png';
    default:
      return '.jpg';
  }
};