How to Upload a File Using PUT/POST Method in POSTMAN: Step-by-Step Guide with Controller Code Example

File uploads are a critical feature in modern web applications, enabling users to share images, documents, and other media. Whether you’re building a social media platform, a document management system, or a cloud storage service, understanding how to handle file uploads via REST APIs is essential.

Postman, a popular API testing tool, simplifies the process of sending file upload requests to your backend server. In this guide, we’ll walk through step-by-step how to upload files using both POST and PUT methods in Postman, with a detailed backend controller code example (using Node.js/Express and Multer for file handling). We’ll also clarify the differences between POST and PUT for file uploads and troubleshoot common issues.

Table of Contents#

  1. Prerequisites
  2. Understanding POST vs. PUT for File Uploads
  3. Backend Setup: Prepare Your Server
    • 3.1 Install Dependencies
    • 3.2 Configure Multer (File Upload Middleware)
    • 3.3 Create POST and PUT Endpoints
  4. Uploading Files with POST in Postman
  5. Uploading Files with PUT in Postman
  6. Controller Code Example (Node.js/Express)
  7. Troubleshooting Common Issues
  8. Conclusion
  9. References

Prerequisites#

Before you begin, ensure you have the following:

  • Postman Installed: Download from Postman’s official site.
  • Basic Knowledge of REST APIs: Familiarity with POST/PUT methods and HTTP requests.
  • Backend Server: We’ll use Node.js with Express (a popular JavaScript framework), but the Postman steps apply to any backend (Python/Flask, Java/Spring, etc.).
  • Node.js & npm: Install from nodejs.org (for the backend example).

Understanding POST vs. PUT for File Uploads#

In REST, the choice between POST and PUT depends on the intended action:

  • POST: Used to create a new resource (e.g., upload a new file to the server). The server assigns a URL/ID to the file.
  • PUT: Used to update or replace an existing resource (e.g., overwrite a previously uploaded file at a specific URL/ID).

For file uploads, the technical steps (in Postman) are nearly identical for both methods—only the HTTP verb and endpoint logic differ.

Backend Setup: Prepare Your Server#

We’ll use Node.js + Express with Multer (a middleware for handling multipart/form-data, required for file uploads). Follow these steps to set up your backend:

3.1 Install Dependencies#

Create a new project folder and initialize Node.js:

mkdir file-upload-demo && cd file-upload-demo
npm init -y

Install required packages:

  • express: Web framework for Node.js.
  • multer: Middleware to handle file uploads.
  • cors: To resolve Cross-Origin Resource Sharing issues (if testing locally).
npm install express multer cors

3.2 Configure Multer#

Multer simplifies handling file uploads by parsing multipart/form-data requests. Create a multer.config.js file to configure storage and file limits:

// multer.config.js
const multer = require('multer');
const path = require('path');
 
// Define storage: where to save uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Save files to the "uploads" directory (create it if it doesn't exist)
    const uploadDir = path.join(__dirname, 'uploads');
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    // Use the original filename (or customize to avoid overwrites)
    // Example: add a timestamp to unique-ify filenames:
    // const uniqueName = `${Date.now()}-${file.originalname}`;
    cb(null, file.originalname); // Using original name for simplicity
  }
});
 
// Filter files (optional: only allow specific file types)
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true); // Accept file
  } else {
    cb(new Error('Only .jpeg, .png, and .pdf files are allowed'), false); // Reject file
  }
};
 
// Configure multer instance
const upload = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB file size limit
  fileFilter: fileFilter
});
 
module.exports = upload;

3.3 Create POST and PUT Endpoints#

Create a server.js file to define your Express server and routes:

// server.js
const express = require('express');
const cors = require('cors');
const upload = require('./multer.config');
const app = express();
const PORT = 3000;
 
// Middleware
app.use(cors()); // Allow cross-origin requests (for local testing)
app.use(express.json()); // Parse JSON bodies (not needed for file uploads, but useful for other routes)
 
// POST Endpoint: Upload a new file
app.post('/upload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }
    res.status(201).json({
      message: 'File uploaded successfully',
      file: {
        name: req.file.originalname,
        path: req.file.path,
        size: req.file.size
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Error uploading file', error: error.message });
  }
});
 
// PUT Endpoint: Update (replace) an existing file
// Assume we identify files by their original name (customize as needed)
app.put('/upload/:fileName', upload.single('file'), (req, res) => {
  try {
    const { fileName } = req.params;
    if (!req.file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }
    // In a real app, check if the file exists before overwriting
    res.status(200).json({
      message: `File "${fileName}" updated successfully`,
      updatedFile: {
        name: req.file.originalname,
        path: req.file.path,
        size: req.file.size
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Error updating file', error: error.message });
  }
});
 
// Start server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Uploading Files with POST in Postman#

Now that your backend is running, use Postman to send a POST request to upload a file:

Step 1: Start the Backend Server#

Run your Express server:

node server.js

You’ll see: Server running on http://localhost:3000.

Step 2: Open Postman and Create a New Request#

  • Launch Postman.
  • Click New > Request.
  • Name the request (e.g., “POST File Upload”) and save it to a collection.

Step 3: Configure the POST Request#

  • Method: Select POST from the dropdown.
  • URL: Enter http://localhost:3000/upload.

Step 4: Set the Request Body#

  • Go to the Body tab.
  • Select form-data (required for file uploads).
  • In the Key field, enter file (must match the upload.single('file') parameter in Multer).
  • Click the dropdown next to the key and select File (default is “Text”).
  • In the Value field, click Select Files and choose a file from your computer (e.g., test-image.png or document.pdf).

Step 5: Send the Request#

Click Send. You’ll see a success response like this:

{
  "message": "File uploaded successfully",
  "file": {
    "name": "test-image.png",
    "path": "uploads/test-image.png",
    "size": 123456
  }
}

Uploading Files with PUT in Postman#

To update (replace) a file, use the PUT endpoint. The steps are nearly identical:

Step 1: Configure the PUT Request#

  • Method: Select PUT.
  • URL: Enter http://localhost:3000/upload/test-image.png (replace test-image.png with the name of the file to update).

Step 2: Set the Request Body#

  • Go to the Body tab, select form-data.
  • Key: file (same as POST).
  • Value: Select a new file (e.g., updated-image.png).

Step 3: Send the Request#

Click Send. The server will overwrite the existing file (if it exists) and return:

{
  "message": "File \"test-image.png\" updated successfully",
  "updatedFile": {
    "name": "updated-image.png",
    "path": "uploads/updated-image.png",
    "size": 789012
  }
}

Controller Code Example (Node.js/Express)#

For larger applications, separate your route logic into controllers. Here’s a refactored example with a fileController.js:

// controllers/fileController.js
exports.uploadFile = (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }
    res.status(201).json({
      message: 'File uploaded successfully',
      file: {
        name: req.file.originalname,
        path: req.file.path,
        size: req.file.size
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Error uploading file', error: error.message });
  }
};
 
exports.updateFile = (req, res) => {
  try {
    const { fileName } = req.params;
    if (!req.file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }
    // Add logic to check if the file exists in your database/storage
    res.status(200).json({
      message: `File "${fileName}" updated successfully`,
      updatedFile: {
        name: req.file.originalname,
        path: req.file.path,
        size: req.file.size
      }
    });
  } catch (error) {
    res.status(500).json({ message: 'Error updating file', error: error.message });
  }
};

Update server.js to use the controller:

// server.js
const express = require('express');
const cors = require('cors');
const upload = require('./multer.config');
const { uploadFile, updateFile } = require('./controllers/fileController');
 
const app = express();
const PORT = 3000;
 
app.use(cors());
 
// Use controller functions
app.post('/upload', upload.single('file'), uploadFile);
app.put('/upload/:fileName', upload.single('file'), updateFile);
 
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Troubleshooting Common Issues#

IssueCauseSolution
400 Bad Request: No file uploadedMissing file in request or wrong field name.Ensure the Key in Postman matches upload.single('file') (e.g., file).
500 Error: ENOENT“uploads” directory doesn’t exist.Create an uploads folder in your project root: mkdir uploads.
CORS ErrorsServer blocks cross-origin requests.Use the cors middleware (as in server.js).
File Size Too LargeMulter’s limits.fileSize exceeded.Increase the limit in multer.config.js (e.g., 10 * 1024 * 1024 for 10MB).
Invalid File TypefileFilter rejected the file.Check allowedTypes in multer.config.js and upload a supported file.

Conclusion#

Uploading files via POST/PUT in Postman is straightforward once you understand the basics: use multipart/form-data in the request body, configure your backend to handle file uploads (with tools like Multer), and choose the appropriate HTTP method (POST for creation, PUT for updates).

By following this guide, you can integrate file uploads into your REST APIs and test them efficiently with Postman.

References#