使用Servlet處理一個(gè)上傳的文件
Servlet中可以使用post請(qǐng)求上傳文件,使用getReader()和getInputStream()自己處理,也可以使用getPart()或getParts()封裝了一些功能的方法處理,getParts()可以同時(shí)上傳多個(gè)文件。接下來使用四個(gè)Demo來練習(xí)一下使用方法
一.使用getReader()和getInputStream()
Demo1
<!-- 這是HTML代碼塊,窗體網(wǎng)頁上顯示的是一個(gè)選擇文件的input框和一個(gè)upload的button --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="filename" value="" /><br> <input type="submit" value="Upload" name="upload" /> </form> </body> </html>
//這是Servlet處理部分
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Servlet implementation class uploadServlet
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//讀取請(qǐng)求Body
byte[] body = readBody(request);
//取得所有Body內(nèi)容的字符串表示
String textBody = new String(body, "ISO-8859-1");
//取得上傳的文件的文件名(取得路徑并分離)
String filename = getFilename(textBody);
//取得文件內(nèi)容在Body中的首尾索引
Position p = getFilePosition(request, textBody);
//將內(nèi)容輸出到文件
writeTo(filename, body, p);
}
//存放索引的類
class Position{
int begin;
int end;
Position(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
//讀取請(qǐng)求body
private byte[] readBody(HttpServletRequest request) throws IOException {
int formDataLength = request.getContentLength();
//獲得ServletInputStream對(duì)象
//getReader()和getInputStream()只能則一調(diào)用,否則會(huì)拋出IllegalStateException異常
DataInputStream dataStream = new DataInputStream(request.getInputStream());
byte[] body = new byte[formDataLength];
int totalBytes = 0;
while(totalBytes < formDataLength) {
int bytes = dataStream.read(body, totalBytes, formDataLength);
totalBytes += bytes;
}
return body;
}
//取得上傳文件名稱
private String getFilename(String reqBody) {
//獲取filename的value,10是filename="的長(zhǎng)度
//通過后臺(tái)調(diào)試我發(fā)現(xiàn)filename=后加的是帶著雙引號(hào)的路徑名,在獲取路徑名時(shí)不需要分號(hào)所以在分離時(shí)就將分號(hào)也分離掉了
String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
//找到文件名這行的末尾,過濾掉對(duì)于獲取文件名而言的無用信息
filename = filename.substring(0, filename.indexOf("\n"));
//獲取不包含路徑名的文件名
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.lastIndexOf("\""));
//此時(shí)后臺(tái)打印分離路徑后的文件名并將其作為返回值返回
System.out.println(filename);
return filename;
}
//取得文件開始和結(jié)束位置
private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
//取得文件區(qū)段邊界信息
String contentType = request.getContentType();
String boundaryText = contentType.substring(
contentType.lastIndexOf("=") + 1, contentType.length());
//取得實(shí)際上傳文件的起始與結(jié)束位置
int pos = textBody.indexOf("filename=\"");
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;
return new Position(begin, end);
}
//輸出至文件
private void writeTo(String filename, byte[] body, Position p) throws IOException {
//默認(rèn)上傳的文件是在F:\\javaeeAroundFiles目錄下
FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename);
fos.write(body, p.begin, (p.end - p.begin));
fos.flush();
fos.close();
}
}
二.使用getPart()和getInputStream()
Demo2
//HTML代碼塊 <!-- 該HTML供uploadPartDemo和uploadPartDemo2共同使用,使用時(shí)通過更改body的form的action屬性值控制 --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="uploadPhoto" method="post" enctype="multipart/form-data"> 上傳相片:<input type="file" name="photo" /><br><br> <input type="submit" value="上傳" name="upload" /> </form> </body> </html>
//uploadPhotoDemo.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartDemo
//Tomcat中必須設(shè)置@MutipartConfig標(biāo)注才能使用getPart()相關(guān)API
@MultipartConfig
@WebServlet("/uploadPhoto")
public class uploadPartDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
//@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//getPart()獲取Part對(duì)象
Part part = request.getPart("photo");
String filename = getFilename(part);
writeTo(filename, part);
}
private String getFilename(Part part) {
String header = part.getHeader("Content-Disposition");
//獲取完整路徑
String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
//filename after substring is: F:\Entertainment\pictures\e5e893df874df44d99f06bc52504a65c.jpg
System.out.println("filename after substring is: " + filename);
//獲取文件名
filename = filename.substring(filename.lastIndexOf("\\") + 1);
//filename after 2 substring is: e5e893df874df44d99f06bc52504a65c.jpg
System.out.println("filename after 2 substring is: " + filename);
return filename;
}
private void writeTo(String filename, Part part) throws IOException, FileNotFoundException {
InputStream is = part.getInputStream();
FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename);
byte[] buffer = new byte[1024];
int length = -1;
while((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
is.close();
fos.close();
}
}
這個(gè)Demo和第一個(gè)代碼最大的區(qū)別就是,通過getPart()方法獲得了Part對(duì)象,通過part對(duì)象的getHeader()方法指定標(biāo)頭獲得對(duì)應(yīng)的值。
在Tomcat中要在Servlet上設(shè)置@MultipartConfig才能取得Part對(duì)象,否則getPart會(huì)得到null
@MultipartConfig含有的屬性如下:
- fileSizeThreshold:整數(shù)值設(shè)置,若上傳文件大小超過設(shè)置門檻,則先寫入緩存文件,默認(rèn)值為0
- location:字符串設(shè)置,設(shè)置寫入文件時(shí)的目錄,使用時(shí)與write方法一起使用,下一個(gè)Demo中演示如何使用,默認(rèn)是空字符串
- maxFileSize:限制上傳文件大小,默認(rèn)-1L即無限制
- maxRequestSize:限制multipart/form-data請(qǐng)求個(gè)數(shù),默認(rèn)值為-1L
Demo3
使用Part的write方法進(jìn)行文件的寫入,HTML文件查看Demo2注釋部分
//uploadPhotoDemo2.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartDemo2
//設(shè)置屬性,這里的最后一級(jí)不用分隔符,可以與Demo2中writeTo方法的路徑做一下對(duì)比
@MultipartConfig(location="F:\\javaeeAroundFiles\\later")
@WebServlet("/uploadPhoto2")
public class uploadPartDemo2 extends HttpServlet {
private static final long serialVersionUID = 1L;
//@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//文件名中可能有中文字符所以進(jìn)行編碼設(shè)置,使用setCharacterEncoding()方法
request.setCharacterEncoding("UTF-8");
Part part = request.getPart("photo");
String filename = getFilename(part);
//使用Part的write方法,寫入location指定路徑
part.write(filename);
}
//獲取文件名與Demo2相同不放代碼
private String getFilename(Part part) {}
}
若要實(shí)現(xiàn)同時(shí)上傳多個(gè)文件則可以使用getParts()方法,獲取到的Part對(duì)象被保存在一個(gè)Collection中
Demo4
<!-- 該HTML是三個(gè)input選框,選擇三個(gè)文件 -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form action="uploadParts" method="post"
enctype="multipart/form-data">
文件1:<input type="file" name="file1" value="" /><br>
文件2:<input type="file" name="file2" value="" /><br>
文件3:<input type="file" name="file3" value="" /><br><br>
<input type="submit" value="上傳" name="upload" />
</form>
</body>
</html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartsDemo
@MultipartConfig(location="F:\\javaeeAroundFiles\\later")
@WebServlet("/uploadParts")
public class uploadPartsDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
//@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//使用foreach遍歷獲取每一個(gè)Part對(duì)象
for(Part part : request.getParts()) {
if(part.getName().startsWith("file")) {
String filename = getFilename(part);
part.write(filename);
}
}
}
//與之前的getFilename()方法相同
private String getFilename(Part part) {
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- 詳解Spring Cloud Stream使用延遲消息實(shí)現(xiàn)定時(shí)任務(wù)(RabbitMQ)
- Spring Cloud CLI簡(jiǎn)單介紹
- spring cloud gateway 限流的實(shí)現(xiàn)與原理
- 詳解Spring Cloud微服務(wù)架構(gòu)下的WebSocket解決方案
- SpringCloud Zuul在何種情況下使用Hystrix及問題小結(jié)
- 詳解Spring Cloud Netflix Zuul中的速率限制
- 詳解Spring Cloud Gateway 數(shù)據(jù)庫存儲(chǔ)路由信息的擴(kuò)展方案
- 詳解SpringCloud Finchley Gateway 統(tǒng)一異常處理
- Spring Cloud Ribbon的踩坑記錄與原理詳析
- Servlet+MyBatis項(xiàng)目轉(zhuǎn)Spring Cloud微服務(wù),多數(shù)據(jù)源配置修改建議
相關(guān)文章
解決FontConfiguration.getVersion報(bào)空指針異常的問題
這篇文章主要介紹了解決FontConfiguration.getVersion報(bào)空指針異常的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
詳解Java?ReentrantLock可重入,可打斷,鎖超時(shí)的實(shí)現(xiàn)原理
前面講解了ReentrantLock加鎖和解鎖的原理實(shí)現(xiàn),但是沒有闡述它的可重入、可打斷以及超時(shí)獲取鎖失敗的原理,本文就重點(diǎn)講解這三種情況,需要的可以了解一下2022-10-10
Spring如何更簡(jiǎn)單的讀取和存儲(chǔ)對(duì)象
這篇文章主要給大家介紹了關(guān)于Spring如何更簡(jiǎn)單的讀取和存儲(chǔ)對(duì)象的相關(guān)資料,在Spring 中想要更簡(jiǎn)單的存儲(chǔ)和讀取對(duì)象的核?是使?注解,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
全網(wǎng)最新Log4j?漏洞修復(fù)和臨時(shí)補(bǔ)救方法
Apache?Log4j?遠(yuǎn)程代碼執(zhí)行漏洞,如何快速修復(fù)log4j2漏洞,本文給大家介紹下Log4j?漏洞修復(fù)和臨時(shí)補(bǔ)救方法,感興趣的朋友跟隨小編一起看看吧2021-12-12

