简单实用H5的FormData对象上传文件

<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');
});


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值