ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)
我以演示上传图片为例子:
java代码如下(前端童鞋可以直接跳过看下面的html及js):
package com.vatuu.web.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class NewsUploadImage * 上传新闻配图 */ @WebServlet("/NewsUploadImage") public class NewsUploadImage extends HttpServlet { private static final long serialVersionUID = 1L; //上传配置 private static final int MEMORY_THRESHOLD = 1024 * 1024 ; // 1MB private static final int MAX_FILE_SIZE = 1024* 200 ; // 200k private static final int MAX_REQUEST_SIZE = 1024 * 1024 ; // 1MB /** * @see HttpServlet#HttpServlet() */ public NewsUploadImage() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 检测是否为多媒体上传 if (!ServletFileUpload.isMultipartContent(request)) { // 如果不是则停止 PrintWriter writer = response.getWriter(); writer.println("Error: 表单必须包含 enctype=multipart/form-data"); writer.flush(); return; } // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 设置临时存储目录 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); // 中文处理 upload.setHeaderEncoding("UTF-8"); // 这个路径相对当前应用的目录 String uploadPath = request.getServletContext().getRealPath("/download/news/images"); // 如果目录不存在则创建 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } PrintWriter pw = response.getWriter(); JSONObject jsonObject = new JSONObject(); try { // 解析请求的内容提取文件数据 @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 迭代表单数据 for (FileItem item : formItems) { // 处理不在表单中的字段 if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); //获取文件后缀名 String prefix=fileName.substring(fileName.lastIndexOf(".")+1); //判断文件类型 if(prefix.equals("jpg") || prefix.equals("gif") || prefix.equals("png") || prefix.equals("jpeg")){ //以时间戳+pt两字命名文件 long currentTime=System.currentTimeMillis(); String filePath = uploadPath + currentTime+"pt."+prefix; File storeFile = new File(filePath); // 在控制台输出文件的上传路径 // 保存文件到硬盘 item.write(storeFile); request.setAttribute("message", "文件上传成功!"); jsonObject.put("fileName", currentTime+"pt."+prefix); jsonObject.put("url", filePath); System.out.println("配图上传成功:" + filePath); }else{ request.setAttribute("message", "不支持该文件类型!"); jsonObject.put("url", ""); System.out.println("配图上传失败,不支持该文件类型!"); } } } } } catch (Exception ex) { request.setAttribute("message", "错误信息: " + ex.getMessage()); jsonObject.put("url", ""); } pw.print(jsonObject.toString()); pw.flush(); pw.close(); } }
一次提交所有表单的HTML如下,表单必须添加enctype属性,才能提交文件:
<form action="${basePath}vatuu/NewsAction?setAction=Add" method="post" name="newsForm" id="newsForm" enctype="multipart/form-data"> <table class="table_border table-form table-td-left table-th-normal"> <tr> <th style="min-width: 150px; width: 20%">新闻标题</th> <td><input type="text" id="newsTitle" name="newsTitle" class="input" style="width:40%"></td> </tr> <tr id="newsContent1"> <th style="width: 20%">新闻内容</th> <td style="width: 80%;" id="newsContent" name="newsContent"><script id="container" name="newsContent" type="text/plain" style="height: 700px; width: 99%;"></script></td> </tr> <tr id="newsUrl1" style="display: none"> <th>链接地址</th> <td><input type="text" style="width: 40%;" id="newsUrl" name="newsUrl" value="http://" class="input" /></td> </tr> <tr> <th style="width: 20%">新闻配图</th> <td> <input type="hidden" id="newsImgUrl" name="newsImgUrl" value=""> <input type="file" class="input" name="newsImage" id="newsImage"/> <a href="javascript:uploadNewsImg()" class="btn btn-blue" >上传配图</a> <img id="showUploadImg" width="80" height="50" style="display: none;" /> <span class="c-red" id="message" name="message"></span> <span>提示:文件大小不超过200k,建议图片宽高为245px*160px</span> </td> </tr> <tr> <td colspan="2" style="text-align: center;"> <input type="submit" class="btn btn-blue" value="发布新闻 "/> <input type="reset" class="btn btn-red" value="取消发布" > </td> </tr> </table> </form>
这里的提交可以直接summit 提交整个表单。
但是也有的时候需要单独上传图片或文件,回显是否上传成功,这里就需要用ajax进行处理。
首先引入jquery。
html跟上个差不多,唯一不同的是,不能给form 添加enctype=“multipart/form-data”属性,因为这里单独上传的时候没问题,但是提交整个表单的时候,若加上这个属性,
则整体提交表单的时候又会上传之前的文件,会出错,因此此处去掉enctype属性。
html如下:
<form action="${basePath}vatuu/NewsAction?setAction=Add" method="post" name="newsForm" id="newsForm" > <table class="table_border table-form table-td-left table-th-normal"> <tr> <th style="min-width: 150px; width: 20%">新闻标题</th> <td><input type="text" id="newsTitle" name="newsTitle" class="input" style="width:40%"></td> </tr> <tr id="newsContent1"> <th style="width: 20%">新闻内容</th> <td style="width: 80%;" id="newsContent" name="newsContent"><script id="container" name="newsContent" type="text/plain" style="height: 700px; width: 99%;"></script></td> </tr> <tr id="newsUrl1" style="display: none"> <th>链接地址</th> <td><input type="text" style="width: 40%;" id="newsUrl" name="newsUrl" value="http://" class="input" /></td> </tr> <tr> <th style="width: 20%">新闻配图</th> <td> <input type="hidden" id="newsImgUrl" name="newsImgUrl" value=""> <input type="file" class="input" name="newsImage" id="newsImage"/> <a href="javascript:uploadNewsImg()" class="btn btn-blue" >上传配图</a> <img id="showUploadImg" width="80" height="50" style="display: none;" /> <span class="c-red" id="message" name="message"></span> <span>提示:文件大小不超过200k,建议图片宽高为245px*160px</span> </td> </tr> <tr> <td colspan="2" style="text-align: center;"> <input type="submit" class="btn btn-blue" value="发布新闻 "/> <input type="reset" class="btn btn-red" value="取消发布" > </td> </tr> </table> </form>
对应的ajax异步请求如下,需要使用jquery中的FormData提交文件(好像jquery必须高于1.2版本)。newsImage则是input type=“file”的id,此处我是上传的图片
//上传新闻配图
function uploadNewsImg(){
var formData = new FormData($( "#newsForm" )[0]);
formData.append("file",$("#newsImage")[0]);
formData.append("name",name);
$.ajax({
url:"../vatuu/NewsUploadImage",
type:"POST",
dataType:"json",
data:formData,
contentType: false,
processData: false,
success:function(data) {
if(data.url !="" && data.url != null){
$("#newsImgUrl").val(data.url);
var url = data.url;
//将上传的文件回显
$("#showUploadImg").css("display","block");
$("#showUploadImg").attr("src","../download/news/images/"+data.fileName);
$("#message").text("上传成功!");
}else{
$("#message").text("上传失败!请仔细检查您的图片类型和大小");
}
}
});
}
将返回的url 设置给之前隐藏的img标签,并把img 标签display: block ,这样就能判断图片是否成功了,最后再sumbit 整个表单就行了,
就可以返回的图片的url 提交给后台了。