如何使用axios从imagePicker上传图像

时间:2020-07-22 02:51:58

标签: react-native axios

我试图用邮递员将文件图像上传到API,但效果很好,但是当我尝试从ImagePicker尝试文件图像时却没用。

我认为创建表格数据时做错了事

处理程序

ImagePicker.showImagePicker(optionsImagePicker, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  } else {
    // const source = { image: response.data };
    let photo = { uri: response.uri}
    let formdata = new FormData();
    
    formdata.append("product[name]", 'test')
    formdata.append("product[price]", 10)
    formdata.append("product[category_ids][]", 2)
    formdata.append("product[description]", '12dsadadsa')
    formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
    

    updateProfilePic(formdata)

    // You can also display the image using data:
    // const source = { uri: 'data:image/jpeg;base64,' + response.data };

    // this.setState({
    //   avatarSource: source,
    // });
  }
});

服务

export function uploadImageProfile(data: any): Promise<any> {

  const config = {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  };
  return api.post('/users/profilepic', {image: data}, config).then((res) => {
    console.log(res.data);
    return res.data;
  });
}

3 个答案:

答案 0 :(得分:0)

您的表单数据必须是这样的。

formdata.append('file',{
    uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
    name: 'test',
    type: 'image/jpeg' // or your mime type what you want
});

然后

axios.post('/users/profilepic', formdata, config).then((res) => {
    console.log(res.data);
    return res.data;
  });

答案 1 :(得分:0)

let formdata = new FormData();

formdata.append('file',{
  uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
  name: 'test',
  type: 'image/jpeg'
});

使用方法:“ POST” 并将formdata.getHeaders()传播到标题中

let reqObj = {
  method: "POST",
  url: 'http://example.com/upload/image',
  headers: { 
    'x-sh-auth': token,
    ...formdata.getHeaders()
  },
  maxContentLength: Infinity,
  maxBodyLength: Infinity
};


  axios(reqObj).then(result => {
    console.log(result)
  }).catch(error => {
    console.log(error)
  });

答案 2 :(得分:0)

我更改了将图像发送到服务器的方式。现在发送im base64并在服务器中使用fs转换为文件。

    const uploadImage = {
      imageBase64: 'data:' + response.type + ';base64,' + response.data,
    };

    updateProfilePic(uploadImage);

服务器端

  async saveImageProfile(imageBase64, logedUserData) {
    let base64Image = imageBase64.imageBase64.split(';base64,').pop();
    let type = imageBase64.imageBase64.split('image/').pop().split(';')[0];
    let newFileName = `${logedUserData.id}.${type}`;
    if (imageFileFilter(type)) {
      const file = await fs.writeFile('./files/' + newFileName, base64Image, { encoding: 'base64' }, function (err) {
        console.log('File created');
      });
      const url = `${baseUrl}/users/files/${newFileName}`;
      this.updateRefProfilePic(url, logedUserData);
    }
    else {
      throw new BadRequestException("Tipo de arquivo não suportado");
    }
  }