【问题标题】:How to convert base64 Image to File object so that I can Send it to Django ImageFeed如何将 base64 图像转换为文件对象,以便我可以将其发送到 Django ImageFeed
【发布时间】:2021-07-15 07:35:21
【问题描述】:

我有 expo 项目,我使用 expo-image-picker 从设备中选择 img,但它只返回 uri and base64 data not actual File,我需要将此图像发送到 django,它应该验证为 ImageField

我尝试使用 b64-to-blob(npm) 将 base64 转换为 blob,但 atob 在 react native android 中不可用,我还尝试使用 fetch API 创建博客,但它在 Andoid 上提供了Network error

let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 0.5,
            base64: true,
        });
console.log(result) 
/*
{
height: "some num",
width: "some num",
...
uri: "file://file_in_device",
base64: "base64 string"
}
*/

【问题讨论】:

    标签: javascript react-native fetch expo blob


    【解决方案1】:

    我们必须使用 multipart/form-data 将文件发送到 API 调用以将图像发送到后端。

    喜欢。

    const data = new FormData()
    data.append("image", {
      name: "test.jpg",
      type: "image/jpg",
      uri: result.uri
    })
    
    await fetch({
        url: 'API END POINT HERE',
        headers: {
          "Accept": "application/json",
          "Content-Type": "multipart/form-data"
        },
        body: data
    })
    

    【讨论】:

    • uri is not a valid ImageFeed django 说:profile_pic: is Not a valid img,这就是为什么发布他的问题我需要将其转换为文件\
    猜你喜欢
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2021-08-31
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多