Java文件上傳與文件下載實現(xiàn)方法詳解
本文實例講述了Java文件上傳與文件下載實現(xiàn)方法。分享給大家供大家參考,具體如下:
Java文件上傳
數(shù)據(jù)上傳是客戶端向服務(wù)器端上傳數(shù)據(jù),客戶端向服務(wù)器發(fā)送的所有請求都屬于數(shù)據(jù)上傳。文件上傳是數(shù)據(jù)上傳的一種特例,指客戶端向服務(wù)器上傳文件。即將保存在客戶端的文件上傳一個副本到服務(wù)器,并保存在服務(wù)器中。
1、上傳表單要求
- 文件上傳要求客戶端提交特殊的請求——multipart請求,即包含多部分數(shù)據(jù)的請求。必須將<form/>標(biāo)簽的enctype屬性值設(shè)為“
multipart/form-data”,enctype表示encodingType,及編碼類型 - 由于客戶端上傳文件的大小是不確定的,所以http協(xié)議規(guī)定,文件上傳的數(shù)據(jù)要存放于請求正文中,不能出現(xiàn)在URL地址欄內(nèi)。也就是說,想要上傳文件必須提交POST請求。
- 表單中要有
<input type="file" />標(biāo)簽 - 注意:
multipart/form-data請求與普通請求不同
2、下載文件上傳jar包并查看官方文檔
打開Apache官網(wǎng)http://www.apache.org/,選擇APACHE PROJECT LIST中的Commons

選擇Commons中的FileUpload項目,并下載jar包和源文件


查看FileUpload的工作方式

查看FileUpload項目的API

3、使用第三方j(luò)ar包上傳文件
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//第一步、判斷請求是否為multipart請求
if(!ServletFileUpload.isMultipartContent(request)) {
throw new RuntimeException("當(dāng)前請求只支持文件上傳");
}
try {
//第二步、創(chuàng)建FileItem工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//設(shè)置臨時文件存儲目錄
String path = this.getServletContext().getRealPath("/Temp");
File temp = new File(path);
factory.setRepository(temp);
//單位:字節(jié)。本例設(shè)置邊界值為2MB,超過該值會創(chuàng)建臨時文件
factory.setSizeThreshold(1024*1024*2);
//第三步、創(chuàng)建文件上傳核心組件
ServletFileUpload upload = new ServletFileUpload(factory);
//設(shè)置item的頭部字符編碼,解決中文亂碼問題
upload.setHeaderEncoding("utf-8");
//設(shè)置單個上傳文件的最大值為5MB
upload.setFileSizeMax(1024*1024*5);
//設(shè)置一次上傳所有文件總和的最大值為10MB(上傳多個文件時起作用)
upload.setFileSizeMax(1024*1024*10);
//第四步、解析請求獲取所有的item
List<FileItem> items = upload.parseRequest(request);
//第五步、遍歷item
for(FileItem item:items) {
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
private void processFormField(FileItem item) {
try {
String name = item.getFieldName();
//解決中文亂碼問題
String value = item.getString("utf-8");
System.out.println(name+"="+value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void processUploadedFile(FileItem item) {
try {
InputStream inputStream = item.getInputStream();
String fieldName = item.getFieldName();
//獲取上傳文件原始名稱
String fileName = item.getName();
//解決文件同名問題
fileName = System.currentTimeMillis()+fileName;
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
String path = this.getServletContext().getRealPath("/UploadContent");
//Date now = new Date();
Calendar now = Calendar.getInstance();
//對上傳的文件進行分類管理
path += "/"+now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH);
//若目錄不存在,則創(chuàng)建該目錄
File directory = new File(path);
if(!directory.exists()) {
directory.mkdirs();
}
File descFile = new File(path,fileName);
OutputStream outputStream = new FileOutputStream(descFile);
int length = -1;
byte[] buffer = new byte[1024];
while((length=inputStream.read(buffer))!=-1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
//刪除臨時文件
item.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java文件下載
數(shù)據(jù)下載是客戶端從服務(wù)器獲取數(shù)據(jù),服務(wù)器向客戶端發(fā)送的所有響應(yīng)都屬于數(shù)據(jù)下載。文件下載是數(shù)據(jù)下載的一種特例,指客戶端從服務(wù)器下載文件,即將保存在服務(wù)器的文件下載一個副本到客戶端。通常我們對服務(wù)器所發(fā)出的請求,大多是文件下載請求,從服務(wù)器中下載文本、圖片、聲音、視頻等文件,客戶端瀏覽器對這些文件進行解析后,我們才能看到多媒體信息。
1、超鏈接下載
- 瀏覽器能解析的文件會直接顯示,如:pdf、jpg......
- 瀏覽器解析不了的文件會被另存為,如:rar、exe......
- 瀏覽器版本不一樣,對文件的解析能力也不同
- 缺點:下載內(nèi)容的形式(直接顯示/另存為)由瀏覽器決定,跟服務(wù)器無關(guān)
2、Servlet方式下載
- 設(shè)置響應(yīng)頭部屬性content-disposition值為attachment
- 獲取連接服務(wù)器源文件的輸入流
- 獲取輸出流
- 將輸入流中的數(shù)據(jù)寫到輸出流中
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DownloadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設(shè)置響應(yīng)的頭部屬性content-disposition值為attachment
//使用filename來指定文件名
String filename = "超跑.png";
byte[] bytes = filename.getBytes("utf-8");
//http協(xié)議規(guī)定瀏覽器只能接受ISO8859-1類型的字節(jié)數(shù)據(jù)
filename = new String(bytes,"ISO8859-1");
response.setHeader("content-disposition", "attachment;filename="+filename);
//獲取連接服務(wù)器資源文件的輸入流
InputStream is = request.getServletContext().getResourceAsStream("/Resources/BS架構(gòu)原理圖1.png");
//獲取輸出流
ServletOutputStream os = response.getOutputStream();
//將輸入流中的數(shù)據(jù)寫到輸出流中
int length = -1;
byte[] buffer = new byte[1024];
while((length=is.read(buffer))!=-1) {
os.write(buffer,0,length);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
解決springmvc整合Mybatis的Log4j日志輸出問題
這篇文章主要介紹了解決springmvc整合Mybatis的Log4j日志輸出問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
springboot接收前端參數(shù)的四種方式圖文詳解
Spring Boot可以通過多種方式接收前端傳遞的數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于springboot接收前端參數(shù)的四種方式,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-11-11
java多線程開發(fā)之通過對戰(zhàn)游戲?qū)W習(xí)CyclicBarrier
這篇文章給大家分享了關(guān)于java多線程開發(fā)中通過對戰(zhàn)游戲?qū)W習(xí)CyclicBarrier的相關(guān)知識點內(nèi)容,有興趣的朋友們學(xué)習(xí)參考下。2018-08-08
MybatisPlus 主鍵策略之type=IdType.ASSIGN_ID等詳解
雪花算法(雪花)是微博開源的分布式ID生成算法其核心思想就是:使用一個64位的長型的數(shù)字作為全局唯一ID,這篇文章主要介紹了MybatisPlus 主鍵策略(type=IdType.ASSIGN_ID等詳解),需要的朋友可以參考下2024-04-04

