I was trying multer for the first time and I got confused on how to upload the selected file. I successfully set up my connection to the backend using ajax and the things I'm confused about are
- Am I assigning the file input data to send to the back end correctly? I am getting the raw value output of the input file element and sending it to the backend currently. Is that the right way?
- When calling the multer upload function on my backend alongside calling
app.post
, what does the "myFile" represent inupload.single('myFile')
currently I'm assuming it is the fileName sent from the client-side. Is that right? - And last how do I assign a specific directory to save the uploaded file in fs? Any help is appreciated. Thanks in advance.
const express = require('express');
const multer = require("multer")
const path = require('path');
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
const port = process.env.PORT || 3000
var cors = require('cors');
app.use(cors());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.listen(port, () => {
console.log('Server is up on port ' + port);
})
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/")
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname)
},
})
const uploadStorage = multer({
storage: storage
})
app.post('/uploadImage', upload.single('myFile'), (req, res, next) => {
try {
res.send(req.body);
console.log(req.body.chooseFileValue)
} catch (error) {
console.log(error);
res.send(400);
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
<h1>Single File Upload Demo</h1>
<form name="mainForm" action="/uploadProfilePicture" enctype="multipart/form-data" method="POST">
<span>Upload Profile Picture:</span>
<input type="file" name="mypic" id="chooseFile" required /> <br>
<button type="button" class="uploadBtn" id="uploadBtn">Upload</button>
</form>
<script>
var chooseFile = document.getElementById('chooseFile')
$('#uploadBtn').click(function() {
console.log(chooseFile.value)
$.ajax({
url: 'http://localhost:3000/uploadImage',
type: 'POST',
"crossDomain": true,
headers: {
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
cache: false,
data: {
"chooseFileValue": chooseFile.value
},
success: function(data) {
console.log(data)
},
error: function(jqXHR, textStatus, err) {
alert('text status ' + textStatus + ', err ' + err)
}
})
});
</script>
</body>
</html>