簡單實用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');
});


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章