jsp中無刷新上傳圖片(前臺使用jquery+ajaxfileupload),後臺用commons-fileupload處理
需求:前臺選擇圖片,頁面顯示上傳後的圖片地址
代碼一:ajaxUploadImg.jspjavascript
請百度搜索,並下載jQuery.js 及 ajaxfileupload.jscss
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script language="javascript" src="<%=basePath%>js/jquery.js" ></script> <script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script> <script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script> <script type="text/javascript"> function ajaxFileUpload() { $("#loading") .ajaxStart(function(){ $(this).show(); })//開始上傳文件時顯示一個圖片 .ajaxComplete(function(){ $(this).hide(); });//文件上傳完成將圖片隱藏起來 $.ajaxFileUpload({ url:'<%=basePath %>FileUpload', //須要連接到服務器地址 secureuri:false, fileElementId:'uploadFileInput', //文件選擇框的id屬性 dataType: 'json', //服務器返回的格式,能夠是json success: function (data, status) //至關於java中try語句塊的用法 { //alert(data); //data是從服務器返回來的值 $('#result').html('上傳圖片成功!請複製圖片地址<br/>'+data.src); }, error: function (data, status, e) //至關於java中catch語句塊的用法 { $('#result').html('上傳圖片失敗'); } } ); } </script> </head> <body> <div id="result" style="FONT:12px 宋體"></div><br/> <img id="loading" src="loading.gif" style="display:none;"> <form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data"> <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" /> <input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="上傳圖片"/> </form> </html>
代碼二: FileUpload.java
這裏使用了commons-fileupload-1.2.1.jar的包,能夠自行搜索下載
若是使用myeclipse,能夠直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jarhtml
package com.lz.servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; public class FileUpload extends HttpServlet { public FileUpload() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); String realDir = request.getSession().getServletContext().getRealPath(""); String contextpath = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextpath + "/"; try { String filePath = "uploadfiles"; String realPath = realDir+"\\"+filePath; //判斷路徑是否存在,不存在則建立 File dir = new File(realPath); if(!dir.isDirectory()) dir.mkdir(); if(ServletFileUpload.isMultipartContent(request)){ DiskFileItemFactory dff = new DiskFileItemFactory(); dff.setRepository(dir); dff.setSizeThreshold(1024000); ServletFileUpload sfu = new ServletFileUpload(dff); FileItemIterator fii = null; fii = sfu.getItemIterator(request); String title = ""; //圖片標題 String url = ""; //圖片地址 String fileName = ""; String state="SUCCESS"; String realFileName=""; while(fii.hasNext()){ FileItemStream fis = fii.next(); try{ if(!fis.isFormField() && fis.getName().length()>0){ fileName = fis.getName(); Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$"); Matcher matcher=reg.matcher(fileName); if(!matcher.find()) { state = "文件類型不容許!"; break; } realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length()); url = realPath+"\\"+realFileName; BufferedInputStream in = new BufferedInputStream(fis.openStream());//得到文件輸入流 FileOutputStream a = new FileOutputStream(new File(url)); BufferedOutputStream output = new BufferedOutputStream(a); Streams.copy(in, output, true);//開始把文件寫到你指定的上傳文件夾 }else{ String fname = fis.getFieldName(); if(fname.indexOf("pictitle")!=-1){ BufferedInputStream in = new BufferedInputStream(fis.openStream()); byte c [] = new byte[10]; int n = 0; while((n=in.read(c))!=-1){ title = new String(c,0,n); break; } } } }catch(Exception e){ e.printStackTrace(); } } response.setStatus(200); String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}"; response.getWriter().print(retxt); } }catch(Exception ee) { ee.printStackTrace(); } } public void init() throws ServletException { // Put your code here } }
代碼三: web.xml作以下java
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>FileUpload</servlet-name> <servlet-class>com.lz.servlet.FileUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUpload</servlet-name> <url-pattern>/FileUpload</url-pattern> </servlet-mapping> </web-app>