将图片从expo Imagepicker上传到Cloudinary

时间:2017-06-22 17:22:06

标签: react-native cloudinary expo

我正在尝试将图像从反应本机应用程序直接上传到cloudinary。我在react-native端使用Expo Imagepicker并使用axios进行POST请求。我从Cloudinary收到" 400 Bad Request" 并显示错误消息 -

  

不支持的源URL:数据%3Aimage%2Fjpg%3Bbase64%2CZmlsZTovLy9kYXRhL3VzZXIvMC9ob3N0LmV4cC5leHBvbmVudC9jYWNoZS9FeHBlcmllbmNlRGF0YS8lMjU0MGFub255bW91cyUyNTJGZXhwb3Rlc3QtZWY2NWJjYjktYTFiMC00N2JlLWE3ZDUtMmNmNThhOGM5ZWU1L0ltYWdlUGlja2VyL2NiN2FmMTUzLTA2OWItNDdlZS05NDdkLWU2ZDk1YTQ1MzI2Yi5qcGc%3D

下面添加了代码

let uri64 = base64.encode(uri);
let fileData = "data:image/jpg;base64," + uri64;
console.log('html escape: ' + encodeURIComponent(fileData));

let data = {
  upload_preset: CLOUDINARY_UPLOAD_PRESET,
  file: encodeURIComponent(fileData)
}
return axios.post(CLOUDINARY_UPLOAD_URL,data);

2 个答案:

答案 0 :(得分:0)

Expo添加了一个从SDK18中的imagepicker生成base64的选项。我编写了一个传递base64的API,它将调用cloudinary方法。

答案 1 :(得分:0)

如果在ImagePicker中指定base64,则可以使用返回的uri和base64数据将图像直接上传到Cloudinary。这是使用超级代理的示例:

const getImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
    base64: true
  })
  if (!result.cancelled) {
    const { uri, base64 } = result
    uploadImage(uri, base64)
  }
}

const uploadImage = (uri, base64) => {
  const uriArr = uri.split('.');
  const fileType = uriArr[uriArr.length - 1]
  const file = `data:${fileType};base64,${base64}`

  let upload = request.post(CLOUDINARY_UPLOAD_URL)
                      .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
                      .field('file', file)
                      .field('folder', CLOUDINARY_FOLDER);
  upload.end((err, response) => {
    if (err) {
      console.error(err)
    }
    if (response.body.secure_url !== '') {
      console.log(response.body.public_id)
    }
  })
}