使用JavaWeb實現文件的上傳和下載
文件上傳
[文件上傳的注意事項]
1.為保證服務器安全,上傳文件應該放在外界無法直接訪問的目錄下, 比如放於WEB-INF目錄下。
2.為防止文件覆蓋的現象發生,要為上傳文件產生一個唯一 的文件名
3.要限制上傳文件的最大值。
4.可以限制上傳文件的類型,在收到上傳文件名時,判斷后綴名是否合法。
文件上傳代碼
1、所需jar包
<!--文件上傳,導入文件上傳的jar包,commons-fileupload , Maven會自動幫我們導入他的依賴包 commons-io包;-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api導入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--jsp的依賴-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!--JSTL的依賴-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- standard標簽庫-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
2、index.jsp
加載服務器地址固定寫法:"${pageContext.request.contextPath}/upload.do"
<html>
<body>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload">
</form>
</body>
</html>
3、FileServlet
package com.lenovo.servlet;
import com.sun.org.apache.xml.internal.res.XMLErrorResources_tr;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判斷上傳的文件是普通表非還是帶文件的表單
if (!ServletFileUpload.isMultipartContent(request)) {
return; //終止方法運行說明這是一個普遠的表單,直接返回
}
//創建上:傳文件的保存路徑,建議在WEB-INF路徑下,安全,用戶無法直接訪問上傳的文件;
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdir(); //創建這個目錄
}
//級存,臨時文件
//臨時路徑,假如文件超過J預期的大小,我們就把他放到一一個臨時文件中,過幾天自動刪除,或者提醒用戶轉存為承久
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
File file = new File(tmpPath);
if (!file.exists()) {
file.mkdir(); //創建這個臨時目錄
}
//處理上傳的文件,一般 都需要通過流來獲取,我們可以使request. getInputstream(),原生態的文件上傳流獲取,十分麻煩
//但是我們都建議使用Apache的文件上:傳組件米實現,common-fileupload, 它需要依賴於commons-io組件:
/*
ServletFileUpload負責處理上傳的文件數據並將表單中每個輸入項封裝成- - 個FileItem對象。
在使用ServletFileUpload對象解析請求時需要DiskFileItemFactory對象。
所以,我們需要在進行解析工作前構造好DiskFileItemFactory對象。
通過ServletFileUpload對象的構造方法或setFileItemFactory()方法設置ServletFileUpload對象的fileItemFactory屬性。
*/
try {
//1.創建DiskFileItemFactory對象,處理文件上傳路徑或者大小限制的;
DiskFileItemFactory factory = getDiskFileItemFactory(file);
//2.獲取ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);
//3.處理上傳的文件
String msg = uploadParseRequest(upload, request, uploadPath);
//servlet請求轉發消息
request.setAttribute("msg", msg);
request.getRequestDispatcher("info.jsp").forward(request, response);
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public static DiskFileItemFactory getDiskFileItemFactory(File file) {
DiskFileItemFactory factory = new DiskFileItemFactory();
//通過這個工廠設置一個緩沖區,當上傳的文件大於這個緩沖區的時候,將他放到臨時文件中;
factory.setSizeThreshold(1024 * 1024); //緩存區大小為1M
factory.setRepository(file);//臨時目錄的保存目錄,需要一個File
return factory;
}
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
//監聽文件上傳進度;
upload.setProgressListener(new ProgressListener() {
@Override
//pBytesRead:已經讀取到的文件大小
//pContentlength :文件大小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("總大小:" + pContentLength + "已上傳:" + pBytesRead);
}
});
//處理亂碼問題
upload.setHeaderEncoding("UTF-8");
//設置單個文件的最大值
upload.setFileSizeMax(1024 * 1024 * 10);
//設置總共能夠上傳文件的大小
//1024=1kb*1024=1M*10=10M
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
throws FileUploadException, IOException {
String msg = "";
//3.把前端請求解析,封裝成一個FileItem對象
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) { //判斷上傳的文件是普通的表單還是帶文件的表單
//getFieldName指的是前端表單控件的name;
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8"); //處理亂碼
System.out.println(name + ":" + value);
} else { //判斷它是上傳的文件
/*====================處理文件========================*/
//拿到文件名字
String uploadFileName = fileItem.getName();
System.out.println("上傳的文件名: " + uploadFileName);
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
//獲得上傳的文件名/images/girl/paojie. png
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
//獲得文件的后綴名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
/*
如果文件后綴名fileExtName 不是我們所需要的
就直接return,不處理,告訴用戶文件類型不對。
*/
System.out.println("文件信息[件名: " + fileName + "---文件類型" + fileExtName + "]");
//可以使用UUID (唯一識別的通用碼),保證文件名唯一;
//UUID. randomUUID(),隨機生一個唯一識別的通 用碼;
String uuidPath = UUID.randomUUID().toString();
/*==================處理文件完-=======================*/
//存到哪? uploadPath
//文件真實存在的路徑realPath
String realPath = uploadPath + "/" + uuidPath;
//給每個文件創建一個對應的文件夾
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
/*====================存放地址完畢-========================*/
//獲得文件上傳的流
InputStream inputStream = fileItem.getInputStream();
//創建一個文件輸出流
//realPath =真實的文件夾;
//差了一個文件;加上輸出文件的名字+"/"+uuidFileName
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
//創建一個緩沖區
byte[] buffer = new byte[1024 * 1024];
//判斷是否讀取完畢
int len = 0;
//如果大於0說明還存在數據;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
//關閉流
fos.close();
inputStream.close();
msg = "文件上傳成功!";
fileItem.delete(); //上傳成功,清除臨時文件
/*====================文件傳輸完==========================*/
}
}
return msg;
}
}
4、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.lenovo.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/upload.do</url-pattern>
</servlet-mapping>
</web-app>
5、info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
6、將文件從本地傳至服務器
文件下載
1、步驟
- 要獲取下載文件的路徑
- 下載的文件名是啥?
- 設置想辦法讓瀏覽器能夠支持(Content-Disposition) 下載我們需要的東西,中文文件
名URLEncoder . encode編碼,否則有可能亂碼 - .獲取下載文件的輸入流
- 創建緩沖區
- 獲取0utputStream對象
- 將FileOutputStream流寫入到buffer緩中區,使用Outputstream將緩沖區中的數據
輸出到客戶端!
2、例題
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要獲取下載文件的路徑
String realPath = "D:\\Project\\IdeaProject\\javaweb-01-servlet\\response\\src\\main\\resource\\西貝.jpg";
System.out.println("下載文件的路徑: " + realPath);
// 2.下載的文件名是啥?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.設置想辦法讓瀏覽器能夠支持(Content -Disposition)下載我們需要的東西,中文文件名URLEncoder . encode編碼,否則有可能亂碼
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 4.獲取下載文件的輸入流
FileInputStream in = new FileInputStream(realPath);
// 5.創建緩沖區
int len = 0;
byte[] buffer = new byte[1024];
// 6.獲取0utputStream對象
ServletOutputStream out = resp.getOutputStream();
// 7.將FileOutputStream流 寫入到buffer緩沖區,使用Outputstream將緩沖區中的數據輸出到客戶端!
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
視頻學習取自:狂神說Java