Skip to content

Instantly share code, notes, and snippets.

@YoshiyukiKato
Last active May 26, 2017 16:20
Show Gist options
  • Save YoshiyukiKato/dc7c827d3d338cf37186bb2ac3f86a9f to your computer and use it in GitHub Desktop.
Save YoshiyukiKato/dc7c827d3d338cf37186bb2ac3f86a9f to your computer and use it in GitHub Desktop.
express file upload sample
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>upload file</title>
</head>
<body>
<input id="filename" type="text" placeholder="filename"/>
<input id="filedata" type="file"/>
<button id="upload">アップロード</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
$("#upload").click(() => {
const fd = new FormData();
const filename = $("#filename").val();
const filedata = $("#filedata")[0].files[0];
fd.append("filename", filename);
fd.append("filedata", filedata);
$.ajax({
type : "POST",
url : "/upload",
processData: false,
contentType : false,
data : fd,
dataType : "json",
success : console.log,
error : console.error
});
});
});
</script>
</body>
</html>
const express = require('express');
const router = express.Router();
const fs = require("fs-extra");
const multiparty = require("multiparty");
router.get('/', (req, res, next) => {
res.sendFile("index.html", {
root : __dirname + "../public"
});
});
router.post('/upload', (req, res, next) => {
const form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
const userFilePath = "./path/to/filedir/" + fields.filename[0];
const tmpFilePath = files.filedata[0].path;
fs.rename(tmpFilePath, userFilePath, (err) => {
if(err){
res.status(500).json({ message : "fail" });
}else{
res.json({ message : "ok" });
}
});
});
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment