nodejs应用:文件上传
功能:上传文件到服务器,图片支持客户端本地预览。
服务端
//server.js
'use strict';
const http = require('http');
const url = require('url');
const util = require('util');
const fs = require('fs');
const formidable = require('formidable');
const path = require('path');
http.createServer(function(req,res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
var form = new formidable.IncomingForm();
form.encoding = 'utf8';
form.uploadDir = path.resolve(__filename,'../dir');
form.keepExtensions = true; //给文件加上对应的扩展名;
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
} else {
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
fs.readFile('./index.html',function(err,data) {
res.end(data);
});
}
}).listen(70,function(){
console.log('ok');
})
客户端
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<input type="file" id="uploadFile"/>
<img style="width:100px;height:auto" id="previewFile" src="" alt=""/>
<input type="button" id="btn" value="提交"/>
</form>
<script src="//cdn.bootcss.com/jquery/2.2.2/jquery.js"></script>
<script>
document.querySelector('#uploadFile').onchange = function() {
var reader = new FileReader();
if (document.querySelector('#uploadFile').files.length > 0){
var source = document.querySelector('#uploadFile').files[0];
reader.readAsDataURL(source);
reader.onload = function(oFREvent) {
document.querySelector('#previewFile').src = oFREvent.target.result;
}
} else {
return;
}
};
document.querySelector('#btn').onclick = function() {
var formData = new FormData();
formData.append('file',$('#uploadFile')[0].files[0]);
formData.append('hello','asddsfs');
$.ajax({
url: '/upload',
type: 'post',
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success:function(data) {
console.log(data);
}
})
}
</script>
</body>
</html>