Initialize the project
Create a name in the current directoryupload-image-api
new folder and initialize a default settingdocument.
mkdir upload-image-api && cd upload-image-api npm init -y
Installation dependencies
express
is a popular web framework;multer
is a middleware for processing file uploads.
npm install express multer
Create an upload image interface
Create a root directoryEntry files and implement simple uploading of pictures.
const express = require("express"); const multer = require("multer"); const path = require("path"); const app = express(); // Set storage path and file nameconst storage = ({ destination: (__dirname, "uploads"), filename: (req, file, cb) => { const uniqueSuffix = () + "-" + (() * 1e9); cb( null, + "-" + uniqueSuffix + () ); }, }); // Create file upload middlewareconst upload = multer({ storage: storage }); /** * Process file upload request * ('image') The `image` in the function is the parameter name of the received file */ ("/upload", ("image"), (req, res, next) => { if (!) { return (400).json({ error: "No file uploaded" }); } const filePath = ; ({ filePath: filePath }); }); // Start the serverconst port = 3000; (port, () => { (`Server is running on port ${port}`); });
Test the upload image interface
- Start the service and execute the command in the terminal:
node
- use
Postman
Or other tools to test the image upload interface. - Towards
http://localhost:3000/upload
sendPOST
request, andmultipart/form-data
Append a name to the formatimage
fields to upload images. - If the request is successful, you will receive a JSON response containing the uploaded file path.
This is the end of this article about using an upload image interface. For more related contents for uploading image interface, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!