【问题标题】:How to upload image with react native?如何使用本机反应上传图像?
【发布时间】:2021-12-26 05:28:31
【问题描述】:

我用这样的 react js 上传图片:

 const onSubmit = (e) => {
    console.log(e.img);
    form.append("file", e.img.originFileObj);
    Axios.post("url", form, {
      headers: {
        Authorization: `bearer ${localStorage.getItem("token")}`,
      },
    })
  };

e.img 的控制台日志是:

现在在 react native 中我使用包 react-native-image-crop-picker 。

在我设置图像文件后,它会给出一个像这样的对象:

{"cropRect": {"height": 960, "width": 960, "x": 0, "y": 160}, "height": 400, "mime": "image/jpeg", "modificationDate": "1636923018000", "path": "file:///storage/emulated/0/Android/data/com.myapp/files/Pictures/33fc6a3f-3673-4756-8343-6f6bcb3c1a7b.jpg", "size": 89454, "width": 400}

现在当我尝试上传图像时,它会给出有关 img 文件的错误。

后端是 node js,我用 multer 处理图像文件,如下所示:

const multer = require('multer');
const uuid = require('uuid');

const MIME_TYPE_MAP = {
    'image/png': 'png',
    'image/jpeg': 'jpeg',
    'image/jpg': 'jpg'
};

const fileUpload = multer({
    limits: 20000000000,
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, 'upload/img');
        },
        filename: (req, file, cb) => {
            const ext = MIME_TYPE_MAP[file.mimetype];
            cb(null, uuid.v4() + '.' + ext);
        }
    }),
    fileFilter: (req, file, cb) => {
        const isValid = !!MIME_TYPE_MAP[file.mimetype];
        let error = isValid ? null : new Error('Invalid mime type!');
        cb(error, isValid);
    }
});

module.exports = fileUpload;

如何像在 react js 中一样在 react native 中发布图像文件?

【问题讨论】:

    标签: javascript node.js reactjs react-native react-native-image-picker


    【解决方案1】:

    解决方案 1

    和 reactjs 一样,在这里你可以像这样使用 FormData 和追加文件:

    asycn function uploadImage() {
      const formData = new FormData();
      const imageData = {
              uri: cropImageData.path, // file uri/path
              name: 'MyImage.jpg', //file name
              type: cropImageData.mime, //file type
            }
      formData.append("file", imageData);
    
      await fetch(url, {
         method: "POST",
         headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: token,
         },
         data: formData,
      }).then((response), {
         console.log(response)
      }).catch((error) => console.log(response));
    }
    

    解决方案 2

    或者你可以从数据中发送base64字符串,(你可以从crop-image picker中获取base64)

    asycn function uploadImage() {
      await fetch(url, {
         method: "POST",
         headers: {
            'Content-Type': 'application/json',
            Authorization: token,
         },
         data: JSON.stringify({
            file: imageBase64String,
         }),
      }).then((response), {
         console.log(response)
      }).catch((error) => console.log(response));
    }
    

    这里你也可以使用 axios 而不是 fetch。

    【讨论】:

      【解决方案2】:

      我是这样解决问题的

      
      
        ImagePicker.openPicker({
                            width: 400,
                            height: 400,
                            cropping: true,
                            includeBase64: true,
                          })
                            .then(image => {
                              setImg(image);
                            })
                            .then(() => setModalVisible(prev => !prev));
      
      
      
       const nn = JSON.stringify(img.path).substring(
              JSON.stringify(img.path).lastIndexOf('/') + 1,
            );
            const image = {
              name: nn,
              uri: img.path,
              type: img.mime,
              size: img.size,
              lastModifiedDate: JSON.parse(img.modificationDate),
              uid: img.modificationDate,
            };
      
        const form = new FormData();
            form.append('file', image);
            axios
              .post('url', form, {
                headers: {
                  Authorization: `bearer ${JSON.parse(token)}`,
                },
              })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-05
        • 2020-03-23
        • 2022-07-18
        • 2020-02-22
        • 2021-05-24
        • 2021-05-24
        • 2018-05-28
        • 2018-07-09
        相关资源
        最近更新 更多