Skip to content

Instantly share code, notes, and snippets.

@sreepurnajasti
Created June 19, 2018 08:27
Show Gist options
  • Save sreepurnajasti/c8e2b6a9fb3b926bca12b2f9486ebb88 to your computer and use it in GitHub Desktop.
Save sreepurnajasti/c8e2b6a9fb3b926bca12b2f9486ebb88 to your computer and use it in GitHub Desktop.
upload single file from client( jquery, ajax) to server(express, multer)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload File</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Upload File</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="uploadFile">
<input type="submit" value="upload">
</form>
</div>
<script src="./main/script/main.js"></script>
</body>
</html>
$(document).ready(function() {
$("#uploadForm").submit(function() {
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url:'/upload',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: data,
success: function(res){
alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
});
const path= require("path");
const multer = require("multer");
const fs = require('fs');
const mkdirp = require("mkdirp");
//set Storage Engine
const storage = multer.diskStorage({
destination: path.join(__dirname,'../../public/storage/') ,
filename: function(req, file, cb){
cb(null, file.originalname);
}
})
const upload = multer({
storage: storage,
limits: {
fileSize: 1000000 //give no. of bytes
},
// fileFilter: function(req, file, cb){
// checkFileType(file, cb);
// }
}).single('uploadFile');
// function checkFileType(file, cb){
// console.log(file);
// // // Allowed extensions
// // const filetypes = /xlsx|xlx|csv/;
// // //check ext
// // var extname = filetypes.test(path.extname(file.originalname).toLocaleLowerCase());
// // var mimetype = filetypes.test(file.mimetype);
// // if(extname mimetype){
// // return cb(null, true);
// // }else{
// // return cb('Error: Invalid file types!');
// // }
// }
function uploadFile(req, res){
upload(req, res, (err) =>{
if(err){
//Send error msg
console.log(err);
res.send(err);
}else{
//send correct msg
//res.send()
res.send('Successful');
console.log('file uploaded succcessfully');
}
});
}
module.exports = {
uploadFile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment