HTML5 檔案非同步上傳 — h5uploader.js
之前寫過一篇H5非同步檔案上傳的文章, 但是很多朋友看著我的這個教程還是出現很多問題,文章寫的不是很好,比較早了。其實通過H5做非同步上傳已經非常簡單了,通過查看文檔,便可以很輕鬆的完成這個功能,當然,如果你不願意查看文檔自己動手的話,那麼就用外掛程式咯。h5uploader是我最近封裝的HTML5上傳外掛程式,代碼才白來行,使用的話也比較簡單,支援檔案大小,類型,progress等等功能。本篇教程,將向你展示Nodejs,Java兩種服務端的上傳方法,並且附有原始碼樣本。
外掛程式下載
如果你是bower的使用者的話,可以直接通過以下命令:
bower install h5uploader --save
當然也可以直接從Github Clone此項目:
git clone https://github.com/wewoor/h5uploader.git
HTML代碼
Upload
以上是一個file類型的input元素以及一個上傳觸發按鈕,後面帶有multiple屬性,表示次處支援檔案多選上傳,當然,你也可以一次提交多個input元素,例如:
Upload
這種方法同樣是可以的,只不過服務端解析的時候要更麻煩。
Javascript
<script type=text/javascript src=html5uploader.js></script> <script type=text/javascript> var uploader = document.getElementById('uploader'); uploader.addEventListener(click, function(e) { H5Uploader.upload({ action: 'upload', id: 'myfile0', size: { max: 5000, // 5000kb valide: function(e) { if (e) { alert(The size of + e.name + is exceed max value!); } } }, // MB type: { name: 'csv;png;jpg', valide: function(e) { if (e) { alert(The type of + e.name + is not supported!); } } }, progress: function() { var p = document.createElement('p'); p.innerHTML = uploading; p.id = loading; document.body.appendChild(p); }, success: function(data) { alert(data); if (data && data == 200) { document.getElementById('loading').innerHTML = The file upload successfully!; alert(The file upload successfully.); } }, fail: function(data) { } }); }, false); </script>
以上是針對單個input元素的上傳,H5Uploader.upload()方法是支援Array類型和Object類型的,也就是說,如果你有多個input元素同時上傳的需求的話,你可以這樣寫:
uploader.addEventListener(click, function(e) { H5Uploader.upload([{ action: 'upload', id: 'myfile0', size: { max: 5000, // 5000kb valide: function(e) { } }, // MB type: { name: 'csv;json', valide: function(e) { } }, progress: function() { }, success: function(data) { }, fail: function(data) { } },{ action: 'upload', id: 'myfile1', size: { max: 5000, // 5000kb valide: function(e) { } }, // MB type: { name: 'png;jpg', valide: function(e) { } }, progress: function() { }, success: function(data) { }, fail: function(data) { } }]); }, false);
Nodejs服務端
服務端是expressjs,利用的一個上傳中介軟體multer
var express = require('express');var multer = require('multer');var app = express();var done = false;app.use(express.static('./public'));// respond with hello world when a GET request is made to the homepageapp.post('/upload',[multer({dest: './uploads/'}), function(req, res) { try { console.log(req.body.myfile); console.log(req.files); res.json(200); } catch (e) { console.log(e); }}]);
完整的範例程式碼,請看
Java servlet樣本
此處沒有用任何架構或者庫,只是Servlet3.0, 用tomcat6的同學要注意哦。
package com.h5uploader.demo;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@MultipartConfigpublic class UploaderServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType(text/html;charset=UTF-8); // Create path components to save the file final String path = /Users/ziv/Desktop/; final Part filePart = req.getPart(myfile0); final String fileName = getFileName(filePart); OutputStream out = null; InputStream filecontent = null; final PrintWriter writer = res.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } writer.println(New file + fileName + created at + path); } catch (FileNotFoundException fne) { writer.println(You either did not specify a file to upload or are + trying to upload a file to a protected or nonexistent + location.); writer.println( ERROR: + fne.getMessage()); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } if (writer != null) { writer.close(); } } } private String getFileName(final Part part) { final String partHeader = part.getHeader(content-disposition); for (String content : part.getHeader(content-disposition).split(;)) { if (content.trim().startsWith(filename)) { return content.substring( content.indexOf('=') + 1).trim().replace(, ); } } return null; }}
以上的上傳樣本是來自官方的代碼,我個人也是測試過的,完整的樣本
另外我還寫了一個sails的版本,有需要的可以點擊查看。
結語
以上則是這個外掛程式使用的全部內容,如果有什麼問題可以直接點擊範例程式碼進行查看,另外外掛程式是我才寫出來的,如果有什麼問題請告訴我。謝謝,希望它能協助你!