ajax异步请求提交上传图片表单并预览图片

ajax异步请求提交上传图片表单并预览图片

一、表单上传文件必须加上enctype="multipart/form-data",(以下是上传文件的表单)

  1. <form action="<%=basePath%>UploadImage" method="post" id="uploadForm" enctype="multipart/form-data">  
  2.     <input type="hidden" name="picture" value="uploadpic">  
  3. <table width="100%" border="0" cellspacing="0" cellpadding="0">  
  4.     <tr>  
  5.             <td width="18%" background="<%=basePath%>tab/images/bg.gif" bgcolor="#FFFFFF"><div align="center"><span class="STYLE1">上传照片</span></div></td>  
  6.            <td bgcolor="#FFFFFF">  
  7.             <input type="file" id="pic" name="pic" />   
  8.             <input type="button" value="上传" onclick="doUpload();">  
  9.            </td>  
  10.         </tr>  
  11. </table>  
  12. </form>  
 <form action="<%=basePath%>UploadImage" method="post" id="uploadForm" enctype="multipart/form-data">
  	<input type="hidden" name="picture" value="uploadpic">
	<table width="100%" border="0" cellspacing="0" cellpadding="0">
		<tr>
          	<td width="18%" background="<%=basePath%>tab/images/bg.gif" bgcolor="#FFFFFF"><div align="center"><span class="STYLE1">上传照片</span></div></td>
            <td bgcolor="#FFFFFF">
            	<input type="file" id="pic" name="pic" /> 
            	<input type="button" value="上传" οnclick="doUpload();">
            </td>
         </tr>
	</table>
	</form>


二、但是使用ajax直接提交表单的数据,在后台会无法获取,因为ajax无法上传文件,经过在网上查阅资料,发现使用ajax提交文件表单必须按照如下代码:(上传按钮单击事件)

[javascript] view plain copy
print ?
  1. <script type="text/javascript">  
  2.     function doUpload() {    
  3.      var formData = new FormData($( "#uploadForm" )[0]);    
  4.      $.ajax({    
  5.           url: '<%=basePath%>UploadImage' ,  /*这是处理文件上传的servlet*/  
  6.           type: 'POST',    
  7.           data: formData,    
  8.           async: false,    
  9.           cache: false,    
  10.           contentType: false,    
  11.           processData: false,    
  12.           success: function (returndata) {    
  13.               document.getElementById("showpic").src="<%=basePath%>UploadImage?picture=showpic";/*这是预览图片用的,自己在文件上传表单外添加*/  
  14.           },    
  15.           error: function (returndata) {    
  16.               alert(returndata);    
  17.           }    
  18.      });    
  19. }    
  20. </script>  
<script type="text/javascript">
	function doUpload() {  
     var formData = new FormData($( "#uploadForm" )[0]);  
     $.ajax({  
          url: '<%=basePath%>UploadImage' ,  /*这是处理文件上传的servlet*/
          type: 'POST',  
          data: formData,  
          async: false,  
          cache: false,  
          contentType: false,  
          processData: false,  
          success: function (returndata) {  
              document.getElementById("showpic").src="<%=basePath%>UploadImage?picture=showpic";/*这是预览图片用的,自己在文件上传表单外添加*/
          },  
          error: function (returndata) {  
              alert(returndata);  
          }  
     });  
}  
</script>
三 处理上传图片的servlet

  1. package com.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.annotation.MultipartConfig;  
  10. import javax.servlet.annotation.WebServlet;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14. import javax.servlet.http.HttpSession;  
  15. import javax.servlet.http.Part;  
  16.   
  17. import com.google.gson.Gson;  
  18.   
  19.   
  20. @WebServlet("/UploadImage")  
  21. @MultipartConfig      
  22. public class UploadImage extends HttpServlet {  
  23.     private static final long serialVersionUID = 1L;  
  24.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  25.         doPost(request, response);  
  26.     }  
  27.   
  28.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  29.         System.out.println("---这里是上传图片的servlet----");  
  30.         String picflag = request.getParameter("picture");  
  31.         String picPath = null;  
  32.         if("uploadpic".equals(picflag)){  
  33.             System.out.println("----上传----");  
  34.             Part part = request.getPart("pic");//前台的文件标签的name,若ajax直接提交表单,这里无法获取  
  35.             String file = part.getHeader("Content-Disposition");  
  36.             //获取文件名  
  37.             String fileName = file.substring(file.lastIndexOf("=")+2, file.length()-1);  
  38.             System.out.println(fileName);  
  39.             //获取项目的部署路劲  
  40.             String basePath = getServletContext().getRealPath("/");  
  41.             System.out.println(basePath);  
  42.             picPath = basePath+fileName;  
  43.             //上传文件到部署路劲  
  44.             part.write(basePath+fileName);  
  45.             //将路径存在session中方便下面显示是用  
  46.             request.getSession().setAttribute("PIC", picPath);  
  47.             //以下代码是使用了  AJax异步请求时使用的  
  48.             Gson gson = new Gson();//创建gson对象  
  49.             response.setContentType("text/json;charset=utf-8");//设置响应的方式为json  
  50.             response.getWriter().print(gson.toJson("<font color=red>用户名或密码错误</font>"));  
  51. //          response.getWriter().write("<script>window.location.href='MyOffice/addPic.jsp';</script>");  
  52.         }else if("showpic".equals(picflag)){  
  53.             System.out.println("这里是上传图片里面显示图片的servlet");  
  54.             //从前台获取图片的路劲(部署项目的根路径)此路劲必须包含到图片,  
  55.             //如D:\My\SOFTWORE\apache-tomcat-7.0.52\wtpwebapps\imas\111.gif  
  56. //          String picPath = request.getParameter("picpath");  
  57.             Object obj = request.getSession().getAttribute("PIC");  
  58.             String picpath = null;  
  59.             if(obj != null && obj instanceof String){  
  60.                 picpath = (String) obj;  
  61.             }  
  62.             System.out.println(picpath);  
  63.             //以该路劲创建一个新文件,只需要找到图片的路劲就可以  
  64.             File file = new File(picpath);  
  65.             response.setCharacterEncoding("gb2312");  
  66.             response.setContentType("doc");  
  67.             response.setHeader("Content-Disposition""attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));  
  68.   
  69.             System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));  
  70.   
  71.             OutputStream output = null;  
  72.             FileInputStream fis = null;  
  73.             try{  
  74.                 output = response.getOutputStream();  
  75.                 fis = new FileInputStream(file);  
  76.           
  77.                 byte[] b = new byte[1024];  
  78.                 int i = 0;  
  79.           
  80.                 while((i = fis.read(b))!=-1){  
  81.                     output.write(b, 0, i);  
  82.                 }  
  83.                 output.write(b, 0, b.length);  
  84.           
  85.                 output.flush();  
  86.                 response.flushBuffer();  
  87.             }  
  88.             catch(Exception e){  
  89.                 System.out.println("Error!");  
  90.                 e.printStackTrace();  
  91.             }  
  92.             finally{  
  93.                 if(fis != null){  
  94.                     fis.close();  
  95.                     fis = null;  
  96.                 }if(output != null){  
  97.                     output.close();  
  98.                     output = null;  
  99.                 }  
  100.             }  
  101.   
  102.         }  
  103.           
  104.           
  105.     }  
  106.   
  107. }  
package com.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.google.gson.Gson;


@WebServlet("/UploadImage")
@MultipartConfig	
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("---这里是上传图片的servlet----");
		String picflag = request.getParameter("picture");
		String picPath = null;
		if("uploadpic".equals(picflag)){
			System.out.println("----上传----");
			Part part = request.getPart("pic");//前台的文件标签的name,若ajax直接提交表单,这里无法获取
			String file = part.getHeader("Content-Disposition");
			//获取文件名
			String fileName = file.substring(file.lastIndexOf("=")+2, file.length()-1);
			System.out.println(fileName);
			//获取项目的部署路劲
			String basePath = getServletContext().getRealPath("/");
			System.out.println(basePath);
			picPath = basePath+fileName;
			//上传文件到部署路劲
			part.write(basePath+fileName);
			//将路径存在session中方便下面显示是用
			request.getSession().setAttribute("PIC", picPath);
			//以下代码是使用了	AJax异步请求时使用的
			Gson gson = new Gson();//创建gson对象
			response.setContentType("text/json;charset=utf-8");//设置响应的方式为json
			response.getWriter().print(gson.toJson("<font color=red>用户名或密码错误</font>"));
//			response.getWriter().write("<script>window.location.href='MyOffice/addPic.jsp';</script>");
		}else if("showpic".equals(picflag)){
			System.out.println("这里是上传图片里面显示图片的servlet");
			//从前台获取图片的路劲(部署项目的根路径)此路劲必须包含到图片,
			//如D:\My\SOFTWORE\apache-tomcat-7.0.52\wtpwebapps\imas\111.gif
//			String picPath = request.getParameter("picpath");
			Object obj = request.getSession().getAttribute("PIC");
			String picpath = null;
			if(obj != null && obj instanceof String){
				picpath = (String) obj;
			}
			System.out.println(picpath);
			//以该路劲创建一个新文件,只需要找到图片的路劲就可以
			File file = new File(picpath);
			response.setCharacterEncoding("gb2312");
			response.setContentType("doc");
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

			System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

			OutputStream output = null;
			FileInputStream fis = null;
			try{
				output = response.getOutputStream();
				fis = new FileInputStream(file);
		
				byte[] b = new byte[1024];
				int i = 0;
		
				while((i = fis.read(b))!=-1){
					output.write(b, 0, i);
				}
				output.write(b, 0, b.length);
		
				output.flush();
				response.flushBuffer();
			}
			catch(Exception e){
				System.out.println("Error!");
				e.printStackTrace();
			}
			finally{
				if(fis != null){
					fis.close();
					fis = null;
				}if(output != null){
					output.close();
					output = null;
				}
			}

		}
		
		
	}

}

四 效果图

上传前



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值