<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<script type="text/javascript">
var input = document.querySelector('input');
var img = document.querySelector('img');
input.onchange = function () {
//获取文件
var file = this.files[0];
//创建读取文件对象
var reader = new FileReader();
//读取文件
reader.readAsDataURL(file);
//在回调函数中修改Img的src属性
reader.onload = function () {
console.log(reader.result);
img.src = reader.result;
}
}
</script>
</head>
<body>
<h3>文件上传:</h3>
<img id="imghead" width=100% height=auto border=0 src='a1.png'>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="imageFile" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
下载代码
var fs = require('fs');
var express = require('express');
const bodyParser=require('body-parser');
const multer=require('multer');
var multerObj = multer({dest: 'uploads/'});
const pathLib=require('path');
var app= express();
/*
[ { fieldname: 'imageFile',
originalname: 'u=685824479,2631081864&fm=27&gp=0.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: 'd92bb2e42b0a18262e5b384b61ebffd2',
path: 'uploads\d92bb2e42b0a18262e5b384b61ebffd2',
size: 9907 } ]
*/
app.use(multerObj.any());
// 单域单文件上传:input[file]的 multiple != "multiple"
app.post('/upload', function(req, res) {
var ext=pathLib.parse(req.files[0].originalname).ext;
var oldPath=req.files[0].path;
var newPath=req.files[0].path+ext;
var newFileName=req.files[0].filename+ext;
fs.rename(oldPath, newPath, (err)=>{
if(err){
res.status(500).send('files opration err').end();
}
else{
res.redirect('/index');
}
});
});
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
app.listen(8080);