图片未使用react-native-image-crop-picker上传到服务器

时间:2019-12-17 10:06:10

标签: react-native

我正在使用react-native-image-crop-picker,我可以从图库中选择图像,但是当尝试通过表单数据上传到服务器时,但该图像没有上传到服务器时,在服务器上显示为空白。有人建议我如何使用react-native-image-crop-picker将多个图像上传到服务器吗?那将是不胜枚举的。谢谢。

3 个答案:

答案 0 :(得分:0)

创建用于处理文件上传的服务

import axios from 'axios'; 
let config = {
    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const uploadService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Baerer '+jwtKey;
    }    
    try{
        return axios.post(
                            url,
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}

在您的View中创建一个上传处理程序,我在下面添加了一个示例

import { uploadService } from '../services/UploadService';

showProfileCropper = (data) => {

    ImagePicker.openCropper({
      path: data.uri,
      freeStyleCropEnabled: true,
      cropping: true,
      width: data.width,
      height: data.height,
      includeExif: true,
    }).then(image => {

      this.setState({
        image: { uri: image.path, width: image.width, height: image.height, mime: image.mime },
        images: null
      });
      this._uploadProfile(image);

    }).catch(e => {
        //console.warn(e)
    });

}


_uploadProfile = async (data) => {


    const jwtKey = '';
    this.setState({ uploading: true });
    let uploadData = new FormData();
    uploadData.append('pageId', this.state.pageId);
    uploadData.append('submit', 'ok');
    uploadData.append('uploadfile', { type: data.mime, uri: data.path, name: data.path.split("/").pop() });


    uploadService(uploadData, '', jwtKey).then((resp) => {
      this.setState({ uploading: false });
      //console.warn(resp.data);
      if (resp.data.success) {
        //this._getPageDataAfterUpload();
      }
    }).catch(err => {
      //console.warn(err);
    });


}


render(){

...........
    <TouchableOpacity
    style={styles.profileImgContain}
    onPress={() => { this.showProfileCropper(this.state.image); }}
    >
    <Text>Choose Image</Text>
    </TouchableOpacity>
...........
}

如果遇到任何困难,请告诉我

答案 1 :(得分:0)

假设后端服务器接受file作为图像参数,并且您尝试将多个图像上传到服务器和服务器上,则实现了多种图像处理,并且您正在使用axios对于API处理,您可以执行以下操作:

const images = await ImageCropPicker.openPicker({
    mediaType: 'photo',
    compressImageQuality: 0.4
});

const data = new FormData();
images.forEach((image, index) => {
    data.append(`file[${index}]`, {
        uri: Platform.OS === 'ios' ? `file:///${image.path}` : image.path,
        type: 'image/jpeg',
        name: 'image.jpg'
    });
});

axios({
    url: 'imageUploadUrl',
    method: 'POST',
    data,
    headers: { 'Content-Type': 'multipart/form-data' }
}).then((response) => {
    console.log('image upload response: ', response)
}).catch((error) => {
    console.log('image upload error: ', error)
});

请不要忘记将imageUploadUrl替换为服务器API URL。

答案 2 :(得分:0)

就我而言,我收到 400 错误,因为在 android 中由于某种原因,文件名字段为空。所以我生成的文件名是不可用的。

name: image.filename || `${Date.now()}.jpg`,

示例:

ImagePicker.openPicker({
  width: 300,
  height: 400,
  cropping: cropping,
  multiple: true,
})
  .then((selImages) => {
    if (selImages && selImages.length == 1) {
      let output = images.slice();
      output[index] = {
        uri: selImages[0].path, // for FormData to upload
        type: selImages[0].mime,
        name: selImages[0].filename || `${Date.now()}.jpg`,
      };
      console.log('ImagePicker.openPicker: output', output);
      onChange(output);
    } else {
      const output = selImages.map((image) => ({
        uri: image.path,
        type: image.mime,
        name: image.filename || `${Date.now()}.jpg`,
      }));
      onChange(output);
      console.log('ImagePicker.openPicker: output', output);
    }
  })
  .catch((e) => console.error('Image Group: ', e));