JavaEE——爬蟲(讀取jsp網頁上上傳的檔案)
阿新 • • 發佈:2018-11-19
讀取jsp網頁上上傳的檔案是不能用request.getParameter(arg0);來讀取的
因為request裡面的鍵值對裡的值只能儲存String陣列,不能儲存檔案
所以接下來就解決這個問題
佈置網頁
<%@ 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%>"> <title>My JSP 'testFileUpload.jsp' starting page</title> <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"> --> </head> <body> <form action="servlet/FileUploadTestServlet" method="post" enctype="multipart/form-data"> 附件<input type="file" name="attachment"/> <br/> <input type="submit"/> <br/> </form> </body> </html>
寫後臺
public class FileUploadTestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //判斷是否為enctype="multipart/form-data" if(!ServletFileUpload.isMultipartContent(request)){ //如果不是,還是取屬性方法不變 }else{ //建立上傳所需的兩個物件 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); //解析器依賴於工廠 //從request的流中解析出表單每個屬性的 名值對(FileItem)。注意:這個值可能是字串,也可能是檔案 List<FileItem> items = sfu.parseRequest(request); for(FileItem item:items){ String name = item.getFieldName();//表單的name屬性的名字(名值對裡的名) // InputStream valueStream = item.getInputStream();//(名值對裡的值)這個是值物件,因為值可以是字串也可以是檔案,所以我們用位元組流的方式來獲取資料 //isFormField()方法是判斷當前表單項是不是字串型別的值 if(item.isFormField()){ String value = item.getString("utf-8");//獲取當前表單項的字串 }else{ String fileName = item.getName();//獲取檔名 String contentType = item.getContentType();//獲取http請求中該檔案的mime型別 File f = new File("e:/aaa/"); if(!f.exists()) f.mkdir(); item.write(new File("e:/aaa/bbb.jpg")); //item.write(new File("e:/aaa/aaa.docx")); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
需要匯入兩個包
注意: