简体   繁体   中英

How to upload react-native image from expo-image-picker to Express.js server using multer

Like the title says, I am trying to upload an image taken from the expo-image-picker on my react-native app to my express.js server that uses multer as middleware. My code for the uploading of the image looks like this:

var data = new FormData();
  data.append('image', { 
    // @ts-ignore 
    uri: listing.image.uri.replace('file://', ''),
    name: listing.title,
    type: listing.image.type,
    description: listing.desc
  })
  const uploadImage = await axios.post(`${env.apiUrl}/uploadImage`, data, {
    cancelToken
  });

Which gets sent to to the express server with this code.

app.post('/uploadImage', upload.single('image'), (req, res) => {
const uploadImage = async (file) => {
  listingService.UploadImage(file)
  .then(payload => {
    return res.status(200).send(payload)
  })
  .catch(payload => {
    return res.status(500).send(payload)
  })
}

const file = req.file;
if(file && file.size < 5000000) {
  uploadImage(file);
}
else {
  res.status(500).send("could not upload file, please enter a file less than 5mb");
}})

and the express server fails with this error:

Request failed with status code 500
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\core\settle.js:17:22 in settle
at node_modules\axios\lib\adapters\xhr.js:62:12 in handleLoad
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:592:4 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

I have this working with postman using the form-data section of the post method but I am unsure how to format the picture that was taken inside the react-native application. Any help is greatly apprectiated.

In your Backend

write like this

const multer = require("multer");

const upload = multer({
  storage: multer.memoryStorage(),
});

app.post("/uploadImage'", upload.array("image"), async (req, res) => {
  try {
     console.log(req.file) // Here you will get the file 
     return res.status(200).send("Done);
  } catch (error) {
    res.status(500).send(error);
  }
});

In your formData

var data = new FormData();
  data.append('image', { 
    // @ts-ignore 
    uri: listing.image.uri, // Don't replace the file with ''..
    name: listing.title,
    type: listing.image.type,
  })
  data.append('description', listing.desc) // Add another key like this
  const uploadImage = await axios.post(`${env.apiUrl}/uploadImage`, data, {
    cancelToken
  });

Somehow, the above did not fully worked for me, I save URI as file with fs.writeFile(), and uri.replace(/^data:image/\w+;base64,/, ""); is needed for image to be displayed, otherwise it does not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM