无法将照片从React Native发送到Cloudinary

时间:2019-11-21 02:25:17

标签: reactjs react-native expo cloudinary

我正在尝试从我的React Native应用程序将图像上传到Cloudinary,但是我收到“ 400错误请求”,说我发送的图像是““ x-cld-error”:“不受支持的源URL “。

ImageUpload.js


    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1
        })

        if (!result.cancelled) {
            setImageSource(result.uri);
        }
    }

我当前正在使用ImagePicker中的expo-image-picker。我要使用从上面获得的imageSource,并将其附加到数据上,然后再将其发送到Cloudinary。 result.uri显示来自iOS模拟器的图片的URL。

CreatePost.js

    const uploadFile = async () => {
        const data = new FormData();
        data.append('file', imageSource);
        data.append('upload_preset', 'test_folder')

        const res = await fetch('https://api.cloudinary.com/v1_1/{my_cloudinary}/image/upload', {
          method: 'POST',
          body: data,
          headers: {
            Accept: 'application/json',
            'Content-Type': 'multipart/form-data',
          },
        })

        const file = await res.json()
        setImage(file.secure_url)
        setLargeImage(file.eager[0].secure_url)
    }

当我console.log res时,它显示状态为400。

1 个答案:

答案 0 :(得分:-1)

您可以尝试使用ajax。例如此处:

<h1>Upload to Cloudinary with FormData</h1>
<div>
<p>

Set your cloud name in the API URL in the code:  "https://api.cloudinary.com/v1_1/<strong>&lt;cloud&nbsp;name&gt;</strong>/image/upload" before running the example.
</p>
</div>
<form action="" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Upload example</legend>
    <p>
      <label for="upload_preset">Unsigned upload Preset: <input type="text" name="upload_preset">(set it <a href="https://cloudinary.com/console/settings/upload#upload_presets">here</a>)</label>
    </p>
    <p>
      <label >Select your photo:
      <input type="file" name="file"></label>
    </p>
    
    <p>
      <input type="submit" value="Submit" />
    </p>
    <img id="uploaded">
    <div id="results"></div>
  </fieldset>
</form>

在此处https://jsfiddle.net/shirlymanor/s1hou7zr/输入代码