JavaWeb文件上傳入門(mén)教程
一、文件上傳原理
1、文件上傳的前提:
a、form表單的method必須是post
b、form表單的enctype必須是multipart/form-data(決定了POST請(qǐng)求方式,請(qǐng)求正文的數(shù)據(jù)類(lèi)型)
c、form中提供input的type是file類(lèi)型的文件上傳域
二、利用第三方組件實(shí)現(xiàn)文件上傳
1、commons-fileupload組件:
jar:commons-fileupload.jar
commons-io.jar
2、核心類(lèi)或接口
DiskFileItemFactory:設(shè)置環(huán)境
public void setSizeThreshold(int sizeThreshold) :設(shè)置緩沖區(qū)大小。默認(rèn)是10Kb。
當(dāng)上傳的文件超出了緩沖區(qū)大小,fileupload組件將使用臨時(shí)文件緩存上傳文件
public void setRepository(java.io.File repository):設(shè)置臨時(shí)文件的存放目錄。默認(rèn)是系統(tǒng)的臨時(shí)文件存放目錄。
ServletFileUpload:核心上傳類(lèi)(主要作用:解析請(qǐng)求的正文內(nèi)容)
boolean isMultipartContent(HttpServletRequest?request):判斷用戶的表單的enctype是否是multipart/form-data類(lèi)型的。
List parseRequest(HttpServletRequest request):解析請(qǐng)求正文中的內(nèi)容
setFileSizeMax(4*1024*1024);//設(shè)置單個(gè)上傳文件的大小
upload.setSizeMax(6*1024*1024);//設(shè)置總文件大小
FileItem:代表表單中的一個(gè)輸入域。
boolean isFormField():是否是普通字段
String getFieldName:獲取普通字段的字段名
String getString():獲取普通字段的值
InputStream getInputStream():獲取上傳字段的輸入流
String getName():獲取上傳的文件名
實(shí)例:先在WEB-INF目錄下建一個(gè)files文件夾,也就是文件都要上傳到這里,也是避免其他人直接訪問(wèn)
1.獲取files的真實(shí)路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.設(shè)置環(huán)境
DiskFileItemFactory factory = new DiskFileItemFactory();//用默認(rèn)的緩存和臨時(shí)文件存儲(chǔ)的地方
3.判斷表單傳送方式
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上傳方式錯(cuò)誤!"); return; }
4.文件上傳核心類(lèi)
ServletFileUpload upload = new ServletFileUpload(factory);5.解析 //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表單提交過(guò)來(lái)的 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); //構(gòu)建輸出流 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();//關(guān)閉流 out.close(); } }
寫(xiě)一個(gè)表單
<%@ 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>
寫(xiě)一個(gè)提交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; //文件上傳入門(mén)案例 public class UploadServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設(shè)置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { //上傳文件的路徑 String storePath = getServletContext().getRealPath("/WEB-INF/files"); //設(shè)置環(huán)境 DiskFileItemFactory factory = new DiskFileItemFactory(); //判斷表單傳送方式 form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上傳方式錯(cuò)誤!"); return; } ServletFileUpload upload = new ServletFileUpload(factory); //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表單提交過(guò)來(lái)的 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); //構(gòu)建輸出流 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();//關(guān)閉流 out.close(); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
上傳的文件是在Tomcat應(yīng)用中。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Javaweb基礎(chǔ)入門(mén)requse原理與使用
- JavaWeb入門(mén):HttpResponse和HttpRequest詳解
- JavaWeb入門(mén):ServletContext詳解和應(yīng)用
- JavaWeb 入門(mén):Hello Servlet
- JavaWeb 入門(mén)篇:創(chuàng)建Web項(xiàng)目,Idea配置tomcat
- JavaWeb入門(mén)教程之分頁(yè)查詢功能的簡(jiǎn)單實(shí)現(xiàn)
- javaWeb使用servlet搭建服務(wù)器入門(mén)
- JavaWeb Spring開(kāi)發(fā)入門(mén)深入學(xué)習(xí)
- Javaweb基礎(chǔ)入門(mén)HTML之table與form
相關(guān)文章
使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄
在本教程中,我們將討論如何使用Spring Security OAuth和Spring Boot實(shí)現(xiàn)SSO - 單點(diǎn)登錄。感興趣的朋友跟隨小編一起看看吧2019-06-06Java struts2 validate用戶登錄校驗(yàn)功能實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了Java struts2 validate用戶登錄校驗(yàn)功能實(shí)現(xiàn)的具體步驟,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05java8新特性-lambda表達(dá)式入門(mén)學(xué)習(xí)心得
這篇文章主要介紹了java8新特性-lambda表達(dá)式入門(mén)學(xué)習(xí)心得,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03Java IO字符流緩沖區(qū)實(shí)現(xiàn)原理解析
這篇文章主要介紹了Java IO字符流緩沖區(qū)實(shí)現(xiàn)原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05Springboot實(shí)現(xiàn)Shiro整合JWT的示例代碼
這篇文章主要介紹了Springboot實(shí)現(xiàn)Shiro整合JWT的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12