Mullti File Upload

 ==============Server.js==========

const express = require('express');
const multer = require('multer');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('uploads'));

///======Upload file with new name
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});

const upload = multer({ storage: storage });


//================Post===========
app.post('/upload', upload.single('image'), (req, res) => {
res.send({ image: req.file.filename });
});
app.post('/uploadMult', upload.array('image'), (req, res) => {
res.send({ image: req.files[0].filename });
});

app.get('/', (req, res) => {
res.sendFile(__dirname+"/index.html");
});

app.listen(3000, () => console.log('Server running on port 3000'));



==================Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Upload File</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<label>Profile</label>
<input type="file" name="image" >


<button type="submit">Upload</button>
</form>

<h1>Fetch Method</h1>
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>


<h1>multiple Upload File</h1>
<form action="/uploadMult" method="POST" enctype="multipart/form-data">
<label>Profile</label>
<input type="file" multiple name="image" >
<button type="submit">Upload</button>
</form>

<script>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];

const formData = new FormData();
formData.append('image', file);

fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>

Comments

Popular posts from this blog

App 1st User Define Component

Example 1

Rabiit