ajax异步请求提交上传图片表单并预览图片
一、表单上传文件必须加上enctype="multipart/form-data",(以下是上传文件的表单)
- <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="上传" onclick="doUpload();">
- </td>
- </tr>
- </table>
- </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提交文件表单必须按照如下代码:(上传按钮单击事件)
- <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>
<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
- 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;
- }
- }
- }
- }
- }
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;
}
}
}
}
}
四 效果图
上传前