why FormData not sent to server, the server receive empty request using put with expo image picker?

Updated: Feb 02, 2025

why FormData not sent to server, the server receive empty request using put with expo image picker?

FormData is a built-in object in JavaScript that allows you to easily construct and send multipart/form-data requests. When using Expo Image Picker to select an image and then trying to send it using FormData with a PUT request, there are several reasons why the server might receive an empty request instead. Here are some common causes and solutions:

  1. Incorrect MIME type: When adding the image to FormData, make sure you set the correct MIME type. For example, if you're sending a JPEG image, use "image/jpeg" as the MIME type.
const image = await ImagePicker.getImageAsync({ mediaTypes: 'Images' });
const formData = new FormData();
formData.append('image', { uri: image.uri, name: 'image.jpg', type: 'image/jpeg' });
  1. File not added to FormData: Make sure you add the image to FormData using the append method.
const image = await ImagePicker.getImageAsync({ mediaTypes: 'Images' });
const formData = new FormData();
formData.append('image', { uri: image.uri, name: 'image.jpg', type: 'image/jpeg' });
  1. Incorrect server-side code: Make sure your server-side code is correctly handling the multipart/form-data request. Use a library like multer in Node.js to parse the incoming request.
const express = require('express');
const multer = require('multer');
const app = express();

const upload = multer({ dest: 'uploads/' });

app.put('/api/upload', upload.single('image'), (req, res) => {
  // process the uploaded image here
});
  1. CORS issues: Make sure your server is configured to allow cross-origin requests if you're making the request from a different domain or port.

  2. Network issues: Make sure there are no network issues preventing the request from being sent or received. You can check the network tab in the browser's developer tools or use a tool like Postman to test the request directly.

  3. Expo server: If you're using Expo's built-in server, make sure you're using the correct headers to send the FormData.

const { NetworkRequest } = require('expo');
const formData = new FormData();
formData.append('image', { uri: image.uri, name: 'image.jpg', type: 'image/jpeg' });

const options = {
  method: 'PUT',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body: formData,
};

NetworkRequest.post('https://your-server.com/api/upload', options)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.error(error));

By following these steps, you should be able to successfully send a FormData request with an image selected using Expo Image Picker and receive it on the server.