JavaWeb文件上傳入門教程
一、文件上傳原理
1、文件上傳的前提:
a、form表單的method必須是post
b、form表單的enctype必須是multipart/form-data(決定了POST請求方式,請求正文的數(shù)據(jù)類型)
c、form中提供input的type是file類型的文件上傳域
二、利用第三方組件實現(xiàn)文件上傳
1、commons-fileupload組件:
jar:commons-fileupload.jar
commons-io.jar
2、核心類或接口
DiskFileItemFactory:設置環(huán)境
public void setSizeThreshold(int sizeThreshold) :設置緩沖區(qū)大小。默認是10Kb。
當上傳的文件超出了緩沖區(qū)大小,fileupload組件將使用臨時文件緩存上傳文件
public void setRepository(java.io.File repository):設置臨時文件的存放目錄。默認是系統(tǒng)的臨時文件存放目錄。
ServletFileUpload:核心上傳類(主要作用:解析請求的正文內(nèi)容)
boolean isMultipartContent(HttpServletRequest?request):判斷用戶的表單的enctype是否是multipart/form-data類型的。
List parseRequest(HttpServletRequest request):解析請求正文中的內(nèi)容
setFileSizeMax(4*1024*1024);//設置單個上傳文件的大小
upload.setSizeMax(6*1024*1024);//設置總文件大小
FileItem:代表表單中的一個輸入域。
boolean isFormField():是否是普通字段
String getFieldName:獲取普通字段的字段名
String getString():獲取普通字段的值
InputStream getInputStream():獲取上傳字段的輸入流
String getName():獲取上傳的文件名
實例:先在WEB-INF目錄下建一個files文件夾,也就是文件都要上傳到這里,也是避免其他人直接訪問
1.獲取files的真實路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.設置環(huán)境
DiskFileItemFactory factory = new DiskFileItemFactory();//用默認的緩存和臨時文件存儲的地方
3.判斷表單傳送方式
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上傳方式錯誤!"); return; }
4.文件上傳核心類
ServletFileUpload upload = new ServletFileUpload(factory);5.解析 //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表單提交過來的 String fieldName = item.getFieldName();//表單信息的字段名 String fieldValue = item.getString(); //表單信息字段值 System.out.println(fieldName+"="+fieldValue); }else//文件處理 { InputStream in = item.getInputStream(); //上傳文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf("\\")+1); //構建輸出流 String storeFile = storePath+"\\"+fileName;//上傳文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//關閉流 out.close(); } }
寫一個表單
<%@ 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 '1.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="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post" enctype="multipart/form-data"> 用戶名<input type="text" name="username"/> <br/> <input type="file" name="f1"/><br/> <input type="file" name="f2"/><br/> <input type="submit" value="保存"/> </form> </body> </html>
寫一個提交servlet:UploadServlet2
package com.liuzhen.upload; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; //文件上傳入門案例 public class UploadServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { //上傳文件的路徑 String storePath = getServletContext().getRealPath("/WEB-INF/files"); //設置環(huán)境 DiskFileItemFactory factory = new DiskFileItemFactory(); //判斷表單傳送方式 form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上傳方式錯誤!"); return; } ServletFileUpload upload = new ServletFileUpload(factory); //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表單提交過來的 String fieldName = item.getFieldName();//表單信息的字段名 String fieldValue = item.getString(); //表單信息字段值 System.out.println(fieldName+"="+fieldValue); }else//文件處理 { InputStream in = item.getInputStream(); //上傳文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf("\\")+1); //構建輸出流 String storeFile = storePath+"\\"+fileName;//上傳文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//關閉流 out.close(); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
上傳的文件是在Tomcat應用中。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用Spring Security OAuth2實現(xiàn)單點登錄
在本教程中,我們將討論如何使用Spring Security OAuth和Spring Boot實現(xiàn)SSO - 單點登錄。感興趣的朋友跟隨小編一起看看吧2019-06-06Java struts2 validate用戶登錄校驗功能實現(xiàn)
這篇文章主要為大家詳細介紹了Java struts2 validate用戶登錄校驗功能實現(xiàn)的具體步驟,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05Springboot實現(xiàn)Shiro整合JWT的示例代碼
這篇文章主要介紹了Springboot實現(xiàn)Shiro整合JWT的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12