【问题标题】:How to Upload Image File To server in react native如何在本机反应中将图像文件上传到服务器
【发布时间】:2021-11-29 12:09:16
【问题描述】:

通过选择图像或文件库我的数据看起来像这样

[{"fileCopyUri": "content://com.android.providers.media.documents/document/image%3A55539", "name": "c6235fa2-aa7f-4e06-a664-7e805de2f883.jpg", "大小”:1967925,“类型”: "image/jpeg", "uri": "content://com.android.providers.media.documents/document/image%3A55539"}]

{"fileCopyUri": "content://com.android.providers.media.documents/document/document%3A55435", "name": "Maha Police-2019 222.pdf", "size": 302194, “类型”:“应用程序/pdf”,“uri”:“内容://com.android.providers.media.documents/document/document%3A55435”}

通过从相机捕获图像我的数据看起来像这样

{“assets”:[{“fileName”:“rn_image_picker_lib_temp_c96a3333-f53f-4143-af29-e0270c8e6a8c.jpg”,“fileSize”:24925,“height”:550,“type”:“image/jpeg”, "uri": "file:///data/user/0/com.sanayaapp/cache/rn_image_picker_lib_temp_c96a3333-f53f-4143-af29-e0270c8e6a8c.jpg", "width": 247}]}

我正在像这样通过 FormData 发送数据


const formData = new FormData();


formData.append('SellerBrandsWeDeal', selectedFile);

fetch('http://api', {
          method: 'POST',
          headers: {Accept: '*/*', 'Content-Type': 'multipart/form-data'},
          body: formData,
})

但它一直说网络错误。请帮忙谢谢

【问题讨论】:

    标签: javascript react-native file-upload multipartform-data form-data


    【解决方案1】:

    您可以使用 rn-fetch-blob 将您的图片编码为 base64 字符串,然后您可以将 base64 字符串发送到服务器。像这样-React-Native: Convert image url to base64 string

    【讨论】:

    • 如果是重复的,使用标志而不是答案。
    【解决方案2】:

    您可以像这样创建图像对象:

        selectedFile = {
                       uri:
    "content://com.android.providers.media.documents/document/image%3A55539",
                        name: "c6235fa2-aa7f-4e06-a664-7e805de2f883.jpg",
                        type: "image/jpeg"
                         }
    

    【讨论】:

      【解决方案3】:

      对我来说,我将图像转换为 base64 并将其作为 blob 上传到数据库。 这里有一个将其转换为 base64 的函数,您只需要实现它即可。它以图像状态存储的转换结果。

      const handleFile = (e) => {
      let file = e.target.files[0];
      getBase64(file)
        .then((result) => {
          // console.log("result",result)
          setImage({
            base64URL: result,
          });
        })
        .catch((err) => {
          setUploadFileError(err);
        });
      

      };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-18
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 2021-03-12
        • 1970-01-01
        • 2020-11-21
        • 2018-08-13
        相关资源
        最近更新 更多