http://blog.csdn.net/aqsunkai/article/details/51779184
Uploadify是JQuery的一個上傳插件,支持ajax無刷新上傳,多個文件同時上傳,上傳進行進度顯示,刪除已上傳文件等。
首先應下載jQuery和uploadify插件
jQuery下載地址:http://www.jq22.com/jquery-info122
Uploadify下載地址:http://www.uploadify.com/,點擊Flash Version
jsp頁面需要引入:
- <script src="<%=basePath%>resources/js/jquery-2.1.4/jquery.min.js"></script>
- <script src="<%=basePath%>resources/js/uploadify/jquery.uploadify.min.js"></script>
- <link type="text/css" rel="stylesheet" href="<%=basePath%>resources/js/uploadify/uploadify.css">
html代碼:
- <div>
- <input type="file" name="uploadify" id="uploadFile" />
- <div id="some_file_queue"></div>
- <div id="fileName"></div>
- <div style="clear: both;margin-top: 20px;cursor: pointer;">
- <a
- class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"
- onclick="javascript:$('#uploadFile').uploadify('upload','*')">
- <span class="glyphicon glyphicon-play"></span> <span
- class="ui-button-text">開始上傳</span>
- </a><a
- class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"
- onclick="javascript:$('#uploadFile').uploadify('cancel','*')">
- <span class="glyphicon glyphicon-ban-circle"></span> <span
- class="ui-button-text">取消上傳</span>
- </a>
- </div>
- </div>
js代碼:
- $(function() {
- $("#uploadFile").uploadify({
- 'swf' : '<%=basePath%>resources/js/uploadify/uploadify.swf',
- 'uploader' : '<%=basePath%>file/uploadFile', //服務器端方法
- //'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},//傳輸數據json格式
- 'height' : 30, //按鈕高度
- 'width' : 100, //按鈕寬度
- 'fileObjName' : 'uploadify',//默認 Filedata, $_FILES控件name名稱
- 'multi' : true, //設置是否允許一次選擇多個文件,true為允許,false不允許
- 'auto' : false, //是否自動上傳
- 'buttonText' : '選擇文件',//按鈕顯示文字
- //'buttonClass' : 'uuid', //按鈕輔助class
- 'buttonCursor' : 'hand', //設置鼠標移到按鈕上的開狀,接受兩個值'hand'和'arrow'(手形和箭頭)
- 'debug' : false, //開啟或關閉debug模式
- 'cancelImg' : '<%=basePath%>resources/js/img/uploadify-cancel.png', //這個沒測試出來,默認是放在與uploadify同級的img文件夾下
- 'fileTypeExts' : '*.jpg;*.jpge;*.gif;*.psd;*.png;*.txt;*.doc;*.docx;*.ppt;*.pptx;*.pdf', //文件后綴限制 默認:'*.*'
- 'fileSizeLimit' : '10MB',//接受一個單位(B,KB,MB,GB)。如果是數字則默認單位為KB。設置為0時表示不限制
- 'fileTypeDesc' : 'All Files',//可選文件的描述。這個值出現在文件瀏覽窗口中的文件類型下拉選項中。(chrome下不支持,會顯示為'自定義文件',ie and firefox下可顯示描述)
- 'method' : 'post', //提交上傳文件的方法,接受post或get兩個值,默認為post
- 'progressData' : 'percentage',//設置文件上傳時顯示數據,有‘percentage’ or ‘speed’兩個參數(百分比和速度)
- 'queueID' : 'some_file_queue',//設置上傳隊列DOM元素的ID,上傳的項目會增加進這個ID的DOM中。設置為false時則會自動生成隊列DOM和ID。默認為false
- 'queueSizeLimit' : 5,//一個隊列上傳文件數限制
- 'simUploadLimit' : 5, //一次同步上傳的文件數目
- 'removeCompleted' : true, //完成時是否清除隊列 默認true
- 'removeTimeout' : 1, //完成時清除隊列顯示秒數,默認3秒
- 'requeueErrors' : false, //設置上傳過程中因為出錯導致上傳失敗的文件是否重新加入隊列中上傳
- 'successTimeout' : 30, //設置文件上傳后等待服務器響應的秒數,超出這個時間,將會被認為上傳成功,默認為30秒
- 'uploadLimit' : 99, //允許上傳的最多張數
- 'onUploadSuccess' : function(file, data, response) { //上傳成功
- var jdata = $.parseJSON(data);
- $("#fileName").append("<p><em name='fileName' onclick = 'downLoadFile(this)' style='color:#555555'>"+jdata.fileName+"</em><em style='color:red' onclick = 'deleteFile(this)'>刪除</em><a name='filePath' style='display:none'>"+jdata.filePath+"</a></p>");
- console.log( 'id: ' + file.id
- + ' - 索引: ' + file.index
- + ' - 文件名: ' + file.name
- + ' - 文件大小: ' + file.size
- + ' - 類型: ' + file.type
- + ' - 創建日期: ' + file.creationdate
- + ' - 修改日期: ' + file.modificationdate
- + ' - 文件狀態: ' + file.filestatus
- + ' - 服務器端消息: ' + data
- + ' - 是否上傳成功: ' + response);
- },
- 'onFallback':function(){
- alert("您未安裝FLASH控件,無法一次性上傳多個文件!請安裝FLASH控件后再試。");
- },
- onSelectError:function(file, errorCode, errorMsg){ //選擇失敗
- switch(errorCode) {
- case -100:
- alert("上傳的文件數量已經超出系統限制的"+$('#uploadFile').uploadify('settings','queueSizeLimit')+"個文件!");
- break;
- case -110:
- alert("文件 ["+file.name+"] 大小超出系統限制的"+$('#uploadFile').uploadify('settings','fileSizeLimit')+"大小!");
- break;
- case -120:
- alert("文件 ["+file.name+"] 大小異常!");
- break;
- case -130:
- alert("文件 ["+file.name+"] 類型不正確!");
- break;
- }
- },
- /* //上傳匯總
- 'onUploadProgress' : function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
- $('#progress').html(totalBytesUploaded + ' bytes uploaded of ' + totalBytesTotal + ' bytes.');
- },
- 'onUploadComplete' : function(file) { //上傳完成
- console.log('The file ' + file.name + ' finished processing.');
- },
- //修改formData數據 ,每個文件即將上傳前觸發
- 'onUploadStart' : function(file) {
- $("#uploadFile").uploadify("settings", "someOtherKey", 2);
- },
- //刪除時觸發
- 'onCancel' : function(file) {
- alert('The file ' + file.name + '--' + file.size + ' was cancelled.');
- },
- //清除隊列
- 'onClearQueue' : function(queueItemCount) {
- alert(queueItemCount + ' file(s) were removed from the queue');
- },
- //調用destroy是觸發
- 'onDestroy' : function() {
- alert('我被銷毀了');
- },
- //每次初始化一個隊列是觸發
- 'onInit' : function(instance){
- alert('The queue ID is ' + instance.settings.queueID);
- },
- //上傳錯誤
- 'onUploadError' : function(file, errorCode, errorMsg, errorString) {
- alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
- }, */
- });
- });
頁面展示:
后台代碼:
上傳方法
- @RequestMapping("/uploadFile")
- public void uploadFile(
- @RequestParam(value = "uploadify", required = false) MultipartFile file,
- HttpServletRequest request, HttpServletResponse response) throws IOException {
- String fileName = file.getOriginalFilename();
- Map<String, Object> dataMap = new HashMap<String, Object>();
- //本機測試路徑
- String path = request.getSession().getServletContext().getRealPath("files");
- String uuid = UUID.randomUUID().toString();
- String filePath = uuid + fileName.substring(fileName.lastIndexOf("."));
- File targetFile = new File(path, filePath);
- if (!targetFile.exists()) {
- targetFile.mkdirs();
- }
- try {
- file.transferTo(targetFile);
- dataMap.put("filePath", filePath);
- dataMap.put("fileName", fileName);
- logger.info("文件上傳成功");
- } catch (Exception e) {
- logger.error(e.getMessage());
- }
- ObjectMapper mapper = new ObjectMapper();
- String data =mapper.writeValueAsString(dataMap);
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().print(data);
- }
下載方法
- @RequestMapping("/downLoadFile")
- public void downLoadFile(HttpServletRequest req,HttpServletResponse resp,FileDTO fileDTO) throws IOException{
- logger.info("/file/downLoadFile");
- PrintWriter pw = null;
- resp.setContentType("text/html,charset=utf-8");
- resp.setCharacterEncoding("UTF-8");
- try {
- String path = req.getSession().getServletContext().getRealPath("/files")+ File.separator +fileDTO.getFilePath();
- File dir = new File(path);
- if (!dir.exists()) {
- pw=resp.getWriter();
- pw.print("<script>alert('抱歉,文件不存在');location.href='javascript:history.go(-1)';</script>);");
- return;
- }
- FileInputStream in = new FileInputStream(path);
- OutputStream fos = resp.getOutputStream();
- resp.reset();
- resp.setContentType("application/x-download");
- resp.setHeader("Content-disposition", "attachment;filename="+getFileName(req,fileDTO.getFileName()));
- byte[] b = new byte[2048];
- int read;
- while ((read = in.read(b)) != -1) {
- fos.write(b,0,read);
- }
- fos.flush();
- in.close();
- fos.close();
- } catch (FileNotFoundException e) {
- System.out.println(e.getMessage());
- pw=resp.getWriter();
- pw.print("<script>alert('抱歉,文件下載失敗');location.href='javascript:history.go(-1)';</script>);");
- }
- }
- public String getFileName(HttpServletRequest req,String channelFileName) throws UnsupportedEncodingException{
- String fileName="";
- String userAgent = req.getHeader("User-Agent");
- //針對IE或者以IE為內核的瀏覽器,加上win10自帶的Edge瀏覽器
- if (userAgent.contains("MSIE")||userAgent.contains("Trident")||userAgent.contains("Edge")) {
- fileName = java.net.URLEncoder.encode(channelFileName, "UTF-8");
- } else {
- //非IE瀏覽器的處理:
- fileName = new String(channelFileName.getBytes("UTF-8"),"ISO-8859-1");
- }
- return fileName;
- }
- package com.cn.entity;
- import java.io.Serializable;
- public class FileDTO implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = -2487063172455865142L;
- private int id;
- private String fileName;
- private String filePath;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public String getFilePath() {
- return filePath;
- }
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
- }