標籤:技術 nts images and 樣本 can 表單 web.xml multipart
JSP+Servlet中使用cos.jar進行圖片上傳
upload.jsp
<form action="FileServlet" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="text" name="cmt" value="example樣本"> <input type="submit"> </form>
enctype:HTML 屬性,規定在發送到伺服器之前應該如何對錶單資料進行編碼。“發送前編碼”
download.jsp
<a href="FileServlet?filename=1.xlsx">download</a>
Servlet:FileServlet.java
import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.jspsmart.upload.File;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String strName = request.getParameter("filename"); if (strName == null) { return; } // new一下 SmartUpload su = new SmartUpload(); // 初始化 su.initialize(getServletConfig(), request, response); // 初始化 su.setContentDisposition(null); try { su.downloadFile("up/" + strName); } catch (SmartUploadException e) { e.printStackTrace(); } // 下載就不用重新導向了,響應已經提交過了,會出錯: // Cannot call sendRedirect() after the response has been committed //response.sendRedirect("upload.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // new一下 SmartUpload su = new SmartUpload(); // 初始化 su.initialize(getServletConfig(), request, response); try { su.upload(); File f = su.getFiles().getFile(0); // SAVE_PHYSICAL 作業系統根目錄 // SAVE_VIRTUAL Web應用根目錄 // SAVE_AUTO 組件自己選擇 f.saveAs("up/" + f.getFileName(), SmartUpload.SAVE_VIRTUAL); } catch (SmartUploadException e) { e.printStackTrace(); } // ↓↓↓取參數 String sevletP = request.getParameter("cmt"); System.out.println("直接擷取參數不可以:" + sevletP); Request request2 = su.getRequest(); String suP = request2.getParameter("cmt"); System.out.println("通過SmartUpload對象間接擷取參數:" + suP); // ↑↑↑取參數 // 轉去下載頁面 response.sendRedirect("download.jsp"); }}
web.xml
<?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"> <servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/FileServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list></web-app>
亂碼問題:這個組件預設使用的編碼是gb2312的,提交檔案,JSP使用GBK可解決檔案名稱亂碼。
檔案夾先建好,會在產生項目中產生這個檔案夾
JSP+Servlet中使用jspsmartupload.jar進行圖片上傳下載