Home > Mobile >  How to upload image with react native?
How to upload image with react native?

Time:11-16

I upload image with react js like this :

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

and the console log for the e.img is :

enter image description here

Now in react native I use the package react-native-image-crop-picker .

and after I set the image file it gives out an object like this :

{"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}

Now When I try to upload the image it gives error about the img file.

And the backend is node js and I handle image files with multer like this :

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;

How can I post the image file in react native like I do in react js ?

CodePudding user response:

Solution 1

Like reactjs, here you can use FormData and append file in that like this:

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));
}

Solution 2

or you can send base64 string from data, (you can get base64 from crop-image picker)

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));
}

here instead of fetch you can use axios too.

CodePudding user response:

I solved the issue this way



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