簡體   English   中英

如何使用本機反應上傳圖像?

[英]How to upload image with react native?

我用這樣的 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 文件的錯誤。

后端是節點 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 中發布圖像文件?

解決方案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 字符串,(您可以從裁剪圖像選擇器中獲取 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。

我這樣解決了這個問題



  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)}`,
          },
        })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM