【问题标题】:Send Image as Raw data Axios React Native将图像作为原始数据发送 Axios React Native
【发布时间】:2022-01-28 18:59:31
【问题描述】:

我的后端接受用于图片上传的原始图片和二进制文件(在 Postman 中工作),但在 React Native 前端我使用react-native-image-crop-picker 来获取图片的uri 等等。

我需要能够以原始或二进制形式发送图像,而不是将其嵌入到 FormData 中。

我正在使用 Axios 来处理我的请求。

我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs react-native axios xmlhttprequest


    【解决方案1】:

    urireact-native-image-crop-picker 返回。获取图像原始数据(BLOB)为

    const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function () {
          resolve(xhr.response);
        };
        xhr.onerror = function (e) {
          reject(new TypeError("Network request failed"));
        };
        xhr.responseType = "blob";
        xhr.open("GET", [IMG_URI_HERE], true);
        xhr.send(null);
      });
    
    //  Your logic to upload BLOB  data to the server
    
      // We're done with the blob, close and release it
      blob.close();
    
    
    

    【讨论】:

      【解决方案2】:

      根据react-native-image-crop-picker可以通过在请求对象中设置includeBase64true得到base64-encoded字符串。

      includeBase64 -- bool (默认 false) -- 当设置为 true 时,图像文件内容将在 data 属性中以 base64 编码字符串的形式提供。提示:要将此字符串用作图像源,请按如下方式使用:data:${image.mime};base64,${image.data}}} />

      ImagePicker.openCamera({
        width: 300,
        height: 400,
        cropping: true,
        includeBase64: true
      }).then(image => {
        console.log(image.data);
      });
      

      【讨论】:

        【解决方案3】:

        您可以将以下代码与react-native-image-crop-picker 库和axios 库一起使用。

        ImagePicker.openPicker({
              compressImageMaxWidth: 300,
              compressImageMaxHeight: 300,
              mediaType: 'photo',
              cropping: true,
            })
              .then(({ path, mime }) => {
                if (path) {
                  const file = {
                    uri: path,
                    name: path,
                    type: mime,
                  };
                  const body = new FormData();
                  body.append('file', file);
                  uploadImage(body);
                }
              })
              .catch((e) => {
                console.log(e.message);
              });
        

        uploadImage 有以下实现

        const uploadImage = (data) => {
          const payload = {
            baseURL: AppConfig.BASE_URL,
            url: '/image',
            method: 'post',
            headers: { 'Content-Type': 'multipart/form-data' },
            timeout: 120000,
            data,
          }
          axios(payload);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-12-20
          • 2022-08-14
          • 1970-01-01
          • 1970-01-01
          • 2020-11-21
          • 2023-03-31
          • 2017-12-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多