0

我正在尝试从 react-native 应用程序将图像直接上传到 cloudinary。我在 react-native 端使用 Expo Imagepicker 并使用 axios 进行 POST 请求。我从 Cloudinary 收到带有错误消息的“400 Bad Request” -

Unsupported source URL: data%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);
4

2 回答 2

0

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

于 2017-07-11T01:33:54.203 回答
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)
    }
  })
}

于 2020-03-05T22:53:46.470 回答