在這裡使用了基於servlet的文件異步上傳,好了廢話不多說,直接上代碼了。 。 。
package com.future.zfs.util;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;@SuppressWarnings("serial")public class FileUploadServlet extends HttpServlet { final long MAX_SIZE = 10 * 1024 * 1024;// 設置上傳文件最大為10M // 允許上傳的文件格式的列表final String[] allowtype = new String[] {"jpg","jpeg","gif","txt","doc","docx","mp3","wma","m4a","xls"}; public FileUploadServlet() { super(); } public void destroy() { super.destroy(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // 設置字符編碼為UTF-8, 這樣支持漢字顯示response.setCharacterEncoding("UTF-8"); // 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// 設置上傳文件時用於臨時存放文件的內存大小,這裡是4K.多於的部分將臨時存在硬盤dfif.setRepository(new File(request.getRealPath("/") + "uploadtemp"));// 設置存放臨時文件的目錄,web根目錄下的uploadtemp目錄// 用以上工廠實例化上傳組件ServletFileUpload sfu = new ServletFileUpload(dfif); // 設置最大上傳尺寸sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // 從request得到所有上傳域的列表List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// 處理文件尺寸過大異常if (e instanceof SizeLimitExceededException) { out.println("{message:'文件尺寸超過規定大小:"+MAX_SIZE+"字節'}"); return; } e.printStackTrace(); } // 沒有文件上傳if (fileList == null || fileList.size() == 0) { out.println("{message:'請選擇上傳文件'}"); return; } // 得到所有上傳的文件Iterator fileItr = fileList.iterator(); // 循環處理所有文件while (fileItr.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // 得到當前文件fileItem = (FileItem) fileItr.next(); // 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { continue; } // 得到文件的完整路徑path = fileItem.getName(); // 得到文件的大小size = fileItem.getSize(); if ("".equals(path) || size == 0) { out.println("{message:'請選擇上傳文件'}"); return; } // 得到去除路徑的文件名String t_name = path.substring(path.lastIndexOf("//") + 1); // 得到文件的擴展名(無擴展名時將得到全名) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); // 拒絕接受規定文件格式之外的文件類型int allowFlag = 0; int allowedExtCount = allowtype.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowtype[allowFlag].equals(t_ext)) break; } if (allowFlag == allowedExtCount) { String message = ""; for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){ message+="*." + allowtype[allowFlag] + " "; } out.println("{message:'請上傳以下類型的文件"+message+"'}"); return; } long now = System.currentTimeMillis(); // 根據系統時間生成上傳後保存的文件名String prefix = String.valueOf(now); // 保存的最終文件完整路徑,保存在web根目錄下的upload目錄下String u_name = request.getRealPath("/") + "upload/" + prefix + "." + t_ext; //原來的文件名path=request.getRealPath("/") + "upload/"+path; try { // 保存文件fileItem.write(new File(path)); response.setStatus(200); out.println("{message:/"文件上傳成功. 已保存為: " + prefix + "." + t_ext + " 文件大小: " + size + "字節/"}"); } catch (Exception e) { e.printStackTrace(); } } }} web.xml
<servlet> <servlet-name>fileUploadServlet</servlet-name> <servlet-class>com.future.zfs.util.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileUploadServlet</servlet-name> <url-pattern>/fileUploadServlet</url-pattern> </servlet-mapping>
上傳頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> <script type="text/javascript"> function ajaxFileUpload() { $("#loading") .ajaxStart(function(){ $(this).show(); })//開始上傳文件時顯示一個圖片.ajaxComplete(function(){ $(this).hide(); });//文件上傳完成將圖片隱藏起來$.ajaxFileUpload ( { url:'fileUploadServlet',//用於文件上傳的服務器端請求地址secureuri:false,//一般設置為false fileElementId:'file',//文件上傳空間的id屬性<input type="file" id="file" name="file" /> dataType: 'json',//返回值類型一般設置為json success: function (data, status) //服務器成功響應處理函數{ //alert(data.message);//從服務器返回的json中取出message中的數據,其中message為在struts2中定義的成員變量$('#myspan').html(data.message); if(typeof(data.error) != 'undefined') { if(data.error != '') { //alert(data.error); $('#myspan').html(data.message); }else { //alert(data.message); $('#myspan').html(data.message); } } }, error: function (data, status, e)//服務器響應失敗處理函數{ //alert(e); $('#myspan').html(e); } } ) return false; } </script> </head> <body> <img src="images/loading.gif" id="loading" style="display: none;"> <span style="color: red;" id="myspan"></span><br/> <input type="file" id="file" name="file" /> <br /> <input type="button" value="上傳" onclick="return ajaxFileUpload();"> <a href="fileDownLoadServlet?filename=通訊錄.xls">哈哈,測試文件下載</a> </body></html>需要注意的是:在使用ajaxFileUpload基於servlet上傳時需要設置response.setContentType("text/html");儘管dataType: 'json'設置為json仍要設置response.setContentType("text/html");否則獲取不到服務器端返回的數據以及會彈出一個對話框。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。