Upload File
Upload File
install
npm install express multer
const express = require("express");
const multer = require("multer");
const path = require("path");
const app = express();
const port = 3000;
// Set up multer storage options
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // Save files in the 'uploads' folder
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // Add timestamp to file name
},
});
// Initialize multer
const upload = multer({ storage });
Upload File EndPoint
app.post("/UploadFile",upload.single('file'),(req,res)=>{
if(!req.file){
return res.status(400).send("Error File Upload.");
}
res.send("File Upload success.");
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Frontend UI
Using Form
<h1>Upload File</h1>
<form action={"http://localhost:8008/UploadFile"} method={"post"} encType="multipart/form-data">
<input type={"file"} name={"file"}/>
<input type={"submit"} value={"upload"}/>
</form>
Using jquery AJAX
Using ajax method
install jquery
npm install jquery
import $ from "jquery";
//------------Api Method-------
export async function Post(form, Method) {
return new Promise(function (success, error) {
$.ajax({
url:Method,
type: "POST",
data: form,
success: function (data, txtstatus, res) {
success(data);
},
error: function (data, txtstatus, res) {
error(data);
},
processData: false,
contentType: false
});
});
}
React Js Component
function UploadFile() {
const refFile=useRef();
async function Upload() {
const file = refFile.current.files[0];
const formData = new FormData();
formData.append("file", file);
try {
const response = await Post(formData, "http://localhost:8008/UploadFile");
alert("File uploaded successfully!");
console.log("Response:", response);
} catch (error) {
console.error("Error uploading file:", error);
alert("Failed to upload the file.");
}
}
return <>
<h1>Ajax Method</h1>
<div>
<input ref={refFile} type={"file"} />
<input onClick={Upload} type={"button"} value={"upload"}/>
</div>
</>
}
Multer optional Configuratio
File Size Validation
const upload = multer({
storage,
limits: { fileSize: 2 * 1024 * 1024 }, // Limit file size to 2MB
});
File Validation
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
const fileTypes = /jpeg|jpg|png|gif/;
const extName = fileTypes.test(path.extname(file.originalname).toLowerCase());
const mimeType = fileTypes.test(file.mimetype);
if (extName && mimeType) {
cb(null, true);
} else {
cb(new Error('Only images are allowed'));
}
},
});
Upload Multiple File
Server.js
app.post('/UploadFileMulti', upload.array('files'), (req, res) => { // 'files' must match the field name used in FormData
if (!req.files || req.files.length === 0) {
return res.status(400).send("No files uploaded.");
}
// Logging the files received for debugging
console.log("Uploaded Files:", req.files);
// Responding with a success message and the file details
res.send({
message: 'Files uploaded successfully!',
files: req.files.map(file => ({
filename: file.filename,
path: file.path,
size: file.size,
originalname: file.originalname,
mimetype: file.mimetype,
}))
});
});
Frontend
<form action={"http://localhost:8008/UploadFileMulti"} method={"post"} encType="multipart/form-data">
<input type={"file"} name={"files"} multiple={true}/>
<input type={"submit"} value={"upload"}/>
</form>
Using AJAX
function UploadFile() {
const refFile=useRef();
async function Upload() {
const files = refFile.current.files;
if (files.length === 0) {
alert("No files selected!");
return;
}
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append("files", files[i]); // 'files' must match the field name in the backend
}
try {
const response = await Post(formData, "http://localhost:8008/UploadFileMulti");
alert("Files uploaded successfully!");
console.log("Response:", response);
} catch (error) {
console.error("Error uploading files:", error);
alert("Failed to upload the files.");
}
}
return <>
<h1>Ajax Method</h1>
<div>
<input ref={refFile} type={"file"} multiple={true} />
<input onClick={Upload} type={"button"} value={"upload"}/>
</div>
</>
}
Comments
Post a Comment