java實(shí)現(xiàn)文件上傳下載
本文實(shí)例為大家分享了java實(shí)現(xiàn)文件上傳下載的具體代碼,供大家參考,具體內(nèi)容如下
一.上傳
1.前端:
<form method="post" action="FileUpload" enctype="multipart/form-data"> <input type="file" name="uploadFile" /> <br/> <input type="submit" value="上傳" /> </form>
2.后臺(tái):
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import dao.FileDao;
@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
public FileUpload() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
out.println("Error: 表單必須包含 enctype=multipart/form-data");
out.flush();
return;
}
// 配置上傳參數(shù)
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設(shè)置內(nèi)存臨界值 - 超過(guò)后將產(chǎn)生臨時(shí)文件并存儲(chǔ)于臨時(shí)目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設(shè)置臨時(shí)存儲(chǔ)目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設(shè)置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設(shè)置最大請(qǐng)求值 (包含文件和表單數(shù)據(jù))
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文處理
upload.setHeaderEncoding("UTF-8");
String uploadPath = request.getServletContext().getRealPath("/files");
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析請(qǐng)求的內(nèi)容提取文件數(shù)據(jù)
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數(shù)據(jù)
for (FileItem item : formItems) {
// 處理不在表單中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制臺(tái)輸出文件的上傳路徑
// System.out.println(filePath);
// 保存文件到硬盤
if(storeFile.exists()) {
out.println("上傳失敗,文件已存在!");
}else {
item.write(storeFile);
out.println("文件上傳成功!");
}
}
}
}
} catch (Exception ex) {
response.getWriter().println("文件上傳成功!");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
二.下載
1.下載鏈接:
FileDownload?filename="+URLEncoder.encode(filename,"utf-8") --------- 需要對(duì)URL中的中文參數(shù)進(jìn)行編碼,否則會(huì)出現(xiàn)亂碼
2.后臺(tái):
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FileDownload")
public class FileDownload extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileDownload() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String dirPath = request.getServletContext().getRealPath("/files");
String filename = URLEncoder.encode(request.getParameter("filename"),"utf-8"); //需要對(duì)URL中的中文參數(shù)進(jìn)行編碼,否則出現(xiàn)亂碼
response.getWriter().println(filename);
String filepath = dirPath + File.separator + filename;
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath);
int i = 0;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java算法實(shí)現(xiàn)調(diào)整數(shù)組順序使奇數(shù)位于偶數(shù)之前的講解
今天小編就為大家分享一篇關(guān)于Java算法實(shí)現(xiàn)調(diào)整數(shù)組順序使奇數(shù)位于偶數(shù)之前的講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01
使用SpringEvent解決WebUploader大文件上傳解耦問(wèn)題
Spring Event是Spring框架內(nèi)建的一種發(fā)布/訂閱模式的實(shí)現(xiàn),它允許應(yīng)用內(nèi)部不同組件之間通過(guò)事件進(jìn)行通信,本文以WebUploader大文件上傳組件為例,在大文件處理的場(chǎng)景中使用SpringEvent的事件發(fā)布機(jī)制,靈活的擴(kuò)展對(duì)文件的處理需求,需要的朋友可以參考下2024-07-07
SpringBoot用JdbcTemplates訪問(wèn)Mysql實(shí)例代碼
本篇文章主要介紹了SpringBoot用JdbcTemplates訪問(wèn)Mysql實(shí)例代碼,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05
JSON的String字符串與Java的List列表對(duì)象的相互轉(zhuǎn)換
這篇文章主要介紹了JSON的String字符串與Java的List列表對(duì)象的相互轉(zhuǎn)換,如果在瀏覽器端JSON是list則轉(zhuǎn)為string結(jié)構(gòu)來(lái)處理,需要的朋友可以參考下2016-04-04
IDEA2023.3.4開(kāi)啟SpringBoot項(xiàng)目的熱部署(圖文)
本文使用的開(kāi)發(fā)工具是idea,使用的是springboot框架開(kāi)發(fā)的項(xiàng)目,配置熱部署,可以提高開(kāi)發(fā)效率,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02
Java移除無(wú)效括號(hào)的方法實(shí)現(xiàn)
本文主要介紹了Java移除無(wú)效括號(hào)的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08

