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



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