我以演示上傳圖片為例子:
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 提交給后台了。
