jsp+servlet+ajaxfileupload.js 實現異步上傳

java代碼:
package yaSoft.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;
import org.apache.commons.io.FileUtils;

import com.ya.pub.conf.FileUploadPath;

/**
 * 新聞內容沒有圖片時
 * 上傳圖片
 * @time 2014-12-29 18:00:25
 * @author lmc
 *
 */
@SuppressWarnings("serial")
public class InformationPicRecommend 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 InformationPicRecommend() {
//        super();
//    }
//
//    public void destroy() {
//        super.destroy(); 
//    }

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

	@SuppressWarnings("rawtypes")
	public void doPost(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.多於的部分將臨時存在硬盤
	    	String ROOT_PATH = FileUploadPath.getKindPath();//緩存臨時文件夾
			String path = ROOT_PATH+"news/"+TimeUtil.getImagesTime()+"/image";
			File directory = new File(path);
			if (!directory.exists()) {
				FileUtils.forceMkdir(directory);
			}
	        dfif.setRepository(directory);// 設置存放臨時文件的目錄,web根目錄下的images目錄
	        // 用以上工廠實例化上傳組件
	        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.print("{message:'文件尺寸超過規定大小:"+MAX_SIZE+"字節'}");
	                return;
	            }
	            e.printStackTrace();
	        }
	        // 沒有文件上傳
	        if (fileList == null || fileList.size() == 0) {
	            out.print("{message:'請選擇上傳文件'}");
	            return;
	        }
	        // 得到所有上傳的文件
	        Iterator fileItr = fileList.iterator();
	        // 循環處理所有文件
	        while (fileItr.hasNext()) {
	            FileItem fileItem = null;
	            String path2 = null;
	            long size = 0;
	            // 得到當前文件
	            fileItem = (FileItem) fileItr.next();
	            // 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)
	            if (fileItem == null || fileItem.isFormField()) {
	                continue;
	            }
	            // 得到文件的完整路徑
	            path2 = fileItem.getName();
	            // 得到文件的大小
	            size = fileItem.getSize();
	            if ("".equals(path) || size == 0) {
	                out.print("{message:'請選擇上傳文件'}");
	                return;
	            }
	            //原來的文件名
	            path=path+"/"+TimeUtil.getPayTime()+path2.substring(path2.indexOf("."), path2.length());
	            try {
	                // 保存文件
	                fileItem.write(new File(path));
	                response.setStatus(200);
	                out.print("{message:\"" + path.substring(path.indexOf("kindfile"), path.length()) + "\"}");
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
				out.flush();
				out.close();
	}
 }
}
web.xml
	<servlet-name>InformationPicRecommend</servlet-name>
		<servlet-class>yaSoft.Util.InformationPicRecommend</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>InformationPicRecommend</servlet-name>
		<url-pattern>/InformationPicRecommend</url-pattern>
	</servlet-mapping>
jsp代碼:
<%@ page contentType="text/html;charset=utf-8" errorPage=""%>
<%@ page import="com.edu.information.*"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="yaSoft.Logic.*,yaSoft.Util.common_util"%>
<%@ page import="java.util.*,java.util.Iterator"%>
<%@ page import="com.ya.pub.conf.FileUploadPath"%>
<%
  String id = PageCommon.getReqValue(request, "id");
  String tab = PageCommon.getReqValue(request, "tab");//當前主畫面的編號
  Map<String, Object> rsltLZ = new HashMap<String, Object>();//獲取新聞的Map
  //新聞ID
  rsltLZ.put("id", id);
  String infoContent = "";
  infoContent = InformationService.getInformationPic(rsltLZ);
  List<String> imgSrcs = new ArrayList<String>(); 
  imgSrcs = common_util.getImgSrc(infoContent);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE></TITLE>
<META http-equiv=Content-Type content="text/html;charset=utf-8">
<script src="../js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="../js/ajaxfileupload.js" type="text/javascript"></script>

</HEAD>
<script type="text/javascript">
//當前畫面編號
var funs = parent.App.getFuns('<%=tab%>');
//確定推薦
function Recommend(type){
	var picUrl = '';
	if(type==1){
		//上傳的圖片
		picUrl=document.getElementById("pic_view").src;
	}else{
		//新聞內容提取圖片
		var radio=document.getElementsByName("radio");
		 for(var i=0;i < radio.length;i++)
		   {
		     if(radio[i].checked){
		    	  	// picUrl=radio[i].value; //這個是value
			    var str = "src_"+(i+1);
			    picUrl = document.getElementById(str).src;
		     }
		   }
	}
	if (funs) {
		funs.infoQXEdit_form_recomForm("",picUrl);
		funs.ns._data.curRecom = 'jsp';//定義全局變量,用於區分當前點擊的推薦時app還是jsp
	} 
}
//上傳新聞配圖
function uploadPic(){
		if($("#pic_file").val() == '')
		if (funs) {
			funs.tuijianTishi();
			return;
		}
		 $.ajaxFileUpload({
			url : '../InformationPicRecommend',
			secureuri : false,// 一般設置爲false
			fileElementId : 'pic_file',// 文件上傳空間的id屬性 <input type="file" id="file"
			// name="file" />
			dataType: 'json',
			success : function(data) // 服務器成功響應處理函數
			{
				$("#picFile").css("display","none");
				var pic = document.getElementById("pic_view");
				pic.src = "../"+data.message;
				$("#r_u").val(pic.src);
				$("#uploadPic").css("display","block");
			},
			error : function(e)// 服務器響應失敗處理函數
			{
				alert(e);
			}
		}); 
}
</script>
<body>
	<%
		if(imgSrcs.size() != 0){
	%>
			<table align="center">
	<%
		int i = 0;
		for(Object o:imgSrcs){
			i++;
			if(i==1){
				
	%>
				<tr>
					<td>
					<input type="radio" id="r_<%=i %>" name="radio" checked="checked" value="<%=o %>"/>
					</td>
					<td>
						<img src="<%=o %>" id="src_<%=i %>" style="width: 100px;height: 80px;" />
					</td>
				</tr>
	<%
			}else{
	%>
				<tr>
					<td>
					<input type="radio" id="r_<%=i %>" name="radio" value="<%=o %>"/>
					</td>
					<td>
						<img src="<%=o %>" id="src_<%=i %>" style="width: 100px;height: 80px;" />
					</td>
				</tr>
	<%
			}
		}
	%>
	</table>
	<center><button οnclick="Recommend(2);">確定</button></center>
	
	<%
		}else{
	%>
		<div id="picFile" style="margin: 0 auto;" align="center">
			<input type="file" id="pic_file" name="pic_file"/>
			<br>
			<button οnclick="uploadPic();">確定</button>
		</div>
	<%
		}
	%>
	
	<div id="uploadPic" style="display: none;">
		<table align="center">
				<tr>
					<td>
					<input type="radio" id="r_u" name="radio1" checked="checked"/>
					</td>
					<td>
						<img src="" id="pic_view"  style="width: 100px;height: 80px;" />
					</td>
				</tr>
		</table>
		<center><button οnclick="Recommend(1);">確定</button></center>
	</div>
</body>
</html>
<pre name="code" class="java">需要注意的是:在使用ajaxFileUpload基於servlet上傳時需要設置response.setContentType("text/html");儘管dataType: 'json'設置爲json仍要設置response.setContentType("text/html");否則獲取不到服務器端返回的數據以及會彈出一個對話框
這點與基於struts2的ajaxFileUpload上傳是不一樣的,可以參考之前寫的http://www.blogjava.net/sxyx2008/archive/2010/11/02/336826.html



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