<pre name="code" class="javascript">使用ajax提交FormData数据
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script type="text/javascript" src="/javascripts/upload.js"></script>
</head>
<body>
<form id="upload">
<p >指定文件名: <input type="text" name="filename" value= "weber"/></p >
<input type="file" name="file" multiple/>
<input type="button" id="submit" value="upload">
</form>
</body>
<script type="text/javascript">
document.getElementById('submit').onclick = function() {
var upload = new Upload('upload', {method:'post', url:'/upload'});
upload.send();
};
</script>
</html>
JavaScript代码
(function(window, undefined) {
function upload(selector, request) {
return new Upload(selector, request);
}
var Upload = function(selector, request) {
this.init(selector);
this.request = request;
}
Upload.prototype.init = function(selector) {
this.form = document.getElementById(selector);
//alert(selector);
//alert(this.form.innerHTML);
};
Upload.prototype.send = function() {
var xhr = getXhr();
var request = this.request;
var formData = new FormData(this.form);
xhr.open(request.method, request.url);
xhr.send(formData);
};
function getXhr() {
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if(window.ActiveXObject){
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
return xhr;
}
window.Upload = upload;
})(window);
nodejs代码
router.post('/upload', function(req, res, next) {
if (req.files && req.files.codecsv != 'undifined') {
var temp_path = req.files.codecsv.path;
if (temp_path) {
fs.readFile(temp_path, 'utf-8', function(err, content) {
//文件的内容
// console.log('content',content);
// 删除临时文件
fs.unlink(temp_path);
});
}
}
res.json('test');
});