天天看點

webUpload元件實作檔案上傳功能和下載下傳功能

一、上傳功能

  1. 首先引用基于jquery的百度上傳元件webuploader(webuploader.css,webuploader.js)(jquery版本要求>1.10,webuploader版本:0.1.5),下載下傳連結:http://www.jq22.com/jquery-info2665
<link rel="stylesheet" type="text/css" href="webuploader.css"/>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="webuploader.js"></script>
           
  1. 建立初始化方法,初始化webuploader插件對象(可以寫在一個js檔案中,外部js檔案引用即可)
//初始化方法
//id:上傳檔案關聯資料id(可選),successCallBack:外部調用的上傳函數,fileType:檔案類型
function initUpload(id,successCallBack){
	var fileType;
	var dhtml = '';
		dhtml += '<div>';
		dhtml += '<table id="file-list" class="table table-bordered"><tr><th width="130px">檔案名稱</th><th>檔案大小</th><th>上傳進度</th></tr></table>';
		dhtml += '<div class="btn btn-primary" id="select-file">選擇檔案</div><div style="margin-left:10px" class="btn btn-primary" id="start-upload">開始上傳</div>';
		dhtml += '</div>';
		//點選上傳跳出的彈窗
		var d = dialog({
			title: '檔案上傳',
			width: 360,
			//加載标簽
			content: dhtml
		})
		//顯示彈窗
		d.showModal();
    //建立并初始化WebUploader對象
 	var fileUploader = WebUploader.create({
  	    // swf檔案路徑(引用下載下傳的webuploader的壓縮包裡的swf檔案)
  	    swf: 'Uploader.swf',
  	    //是否允許重複的圖檔
  	  	duplicate :true,
  	  	// 選完檔案後,是否自動上傳
  	    auto: false,
  	    // 檔案上傳的伺服器位址。
  	    server: "UploadServlet",
  	    // 選擇檔案的按鈕。可選。
  	    // 内部根據目前運作是建立,可能是input元素,也可能是flash.
  	    pick: '#select-file',
  	    // 不壓縮image, 預設如果是jpeg,檔案上傳前會壓縮一把再上傳!
  	    resize: false,
  	    //上傳檔案類型
  	    accept: fileType || null,
  	    /*//線程數
        threads: 1,
        //單個檔案大小限制
        fileSingleSizeLimit: 2000,
        //上傳檔案數量限制
        fileNumLimit:10,
        //上傳前不壓縮
        compress:false,*/
  	});
  	//監聽WebUploader事件:
  	//當有一批檔案加載進隊列時觸發事件
  	fileUploader.on( 'fileQueued', function( file ) {
  		var html = '';
  		var attachmentSize = WebUploader.formatSize(file.size);
  		html += '<tr id="' + file.id +'"><td>' +file.name+'<b></b></td><td>'+attachmentSize+'</td><td><div class="progress" style="margin-bottom:0"><div class="progress-bar" style="width: 0%"></div></div></td></tr>';
		$(html).appendTo('#file-list');
  	});
  	// 檔案上傳過程中建立進度條實時顯示。
  	fileUploader.on( 'uploadProgress', function( file, percentage ) {
  		$("#"+file.id).find('b').html('<span>' + percentage*100 + '%</span>');
		$('#'+file.id+' .progress').find(".progress-bar").css('width',percentage*100 + '%');//控制進度條
  	});
  	// 檔案開始上傳時執行。
  	fileUploader.on( 'uploadStart', function( file ) {
  	    
  	});
  	// 檔案上傳成功時執行。
  	fileUploader.on( 'uploadSuccess', function(file,response) {
  		var filePath = response.id;
  		if(response.error == 0){
  	  		successCallBack(file,filePath);
  		}else{
  			alert(response.message,3);
  		}
  	});
  	// 檔案上傳失敗時執行。
  	fileUploader.on( 'uploadError', function( file ) {
  	    fileType = file.type;
  	});
  	//錯誤處理
  	fileUploader.on('error', function( code ) {
        var text = '';
        var message = '';
        if(fileType){
        	message = fileType.extensions
        }else{
        	message = "doc,docx"
        }
        switch( code ) {
          case  'F_DUPLICATE' : text = '該檔案已經被選擇了!' ;
          break;
          case  'Q_EXCEED_NUM_LIMIT' : text = '上傳檔案數量超過限制!' ;
          break;
          case  'Q_EXCEED_SIZE_LIMIT' : text = '所有檔案總大小超過限制!';
          break;
          case 'Q_TYPE_DENIED' : text = '請上傳'+'  '+message+'  '+'類型的檔案';
          break;
          default : text = '未知錯誤!';
          break;  
        }
        alert(text,3);
      });
  	// 所有檔案上傳完成觸發
  	fileUploader.on( 'uploadFinished', function( file ) {
  		d.remove();
  	});
  	
  	$("#start-upload").click(function(){
  		//調用WebUploader的upload()方法,開始上傳此方法可以從初始狀态調用開始上傳流程,也可以從暫停狀态調用,繼續上傳流程。
  		//可以指定開始某一個檔案。
  		fileUploader.upload();
  	})
}
           

未涉及的方法或參數請看官方文檔:http://fex.baidu.com/webuploader/doc/index.html

3. HTML頁面

<table border='1' id='theTable'>
	<tr>
		<th>id</td>
		<th>操作</td>
	</tr>
	<tr>
		<td>1</td>
		<td><a style="cursor:pointer;color:#337ab7;" id="upload" class="upload"/>上傳</a></td>
	</tr>
</table>
           
  1. 頁面上傳函數
$('.upload').live("click", function() {
	var id = $(this).closest("tr").find("td").eq(0).text();
	initUpload(id,uploadFile);
});
//将上傳的檔案資訊及上傳路徑傳入後端,後端經過處理錄入資料庫
function uploadFile(file, filePath) {
    var fileName = file.name;
    $.ajax({
        url : "/service/serviceMethod/"+id+"/"+fileName+"/"+filePath,
        type : "POST",
        contentType : "application/json",
        data : JSON
        success: function(data){
            alert("附件上傳成功",1);
            location.reload();
        },
        error : function() {
            alert("上傳檔案異常!",3);
        }
    });
}
           

二、下載下傳功能

  1. 頁面函數
function download(obj){
	var url= '';
	if(typeof(obj.filePath) != "undefined") {
		url = obj.filePath;
	} else if(typeof($(obj).attr("name")) != "undefined"){
		url = $(obj).attr("name");	
	}
	if(url == '') {
		return ;
	}
	if(url.indexOf("\\")>-1){
		url = url.replace(/\\/g,"/");
	}
	if (url.indexOf("upload/") >= 0 || url.indexOf("temp/") >= 0) {
		var url = "/downloadServlet?filePath=" + url;
		downloadContent(url);
	}else{
		alert("檔案路徑錯誤,下載下傳失敗",3);
	}
}
           
  1. java後端downloadServlet代碼
/**
 * 下載下傳檔案
 */
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
	//編碼格式
	private String code = "utf-8";
	
	public DownloadServlet() {
		super();
	}

	public void init(ServletConfig config) throws ServletException {

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		InputStream  systemConfig= request.getServletContext().getResourceAsStream("/WEB-INF/classes/systemConfig.properties");
		Properties properties = new Properties();
		//加載properties檔案
		properties.load(systemConfig);
		//檔案下載下傳後存放路徑
		String fileSystemPath = pro.getProperty("fileSystemPath");
		//下載下傳路徑
		String filePath = request.getParameter("filePath");
		File file = new File(fileSystemPath + File.separator + filePath);
		/* 如果檔案存在 */
		if (file.exists()) {
			//設定檔案内容編碼格式
			String fileName = URLEncoder.encode(file.getName(), code);
			//清除下載下傳後檔案首部的空白行
			response.reset();
			ServletContext servletContext=request.getServletContext();
			//使用戶端浏覽器通過MIME類型來處理json字元串
			response.setContentType(servletContext.getMimeType(fileName));  
			//附件下載下傳
			response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
			int fileLength = (int) file.length();
			response.setContentLength(fileLength);
			/* 如果檔案長度大于0 */
			if (fileLength > 0) {
				/* 建立輸入流 */
				InputStream inStream = null;
				ServletOutputStream outStream = null;
				try {
					inStream = new FileInputStream(file);
					byte[] buf = new byte[4096];
					/* 建立輸出流 */
					outStream = response.getOutputStream();
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						outStream.write(buf, 0, readLength);
					}
				} finally {
					inStream.close();
					outStream.flush();
					outStream.close();
				}
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
           
  1. systemConfig.properties檔案

    fileSystemPath=D:/downLoadFile

繼續閱讀