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

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

 
上传照片


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

三 处理上传图片的servlet

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("用户名或密码错误"));
//			response.getWriter().write("");
		}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;
				}
			}

		}
		
		
	}

}

四 效果图

上传前



你可能感兴趣的:(ajax异步请求提交上传图片表单并预览图片)