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);
// 保存文件到硬盤(pán)
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)文章
springcloud中Feign超時(shí)提示Read timed out executing
Feign接口調(diào)用分兩層,Ribbon的調(diào)用和Hystrix調(diào)用,理論上設(shè)置Ribbon的時(shí)間即可,但是Ribbon的超時(shí)時(shí)間和Hystrix的超時(shí)時(shí)間需要結(jié)合起來(lái),這篇文章給大家介紹springcloud之Feign超時(shí)提示Read timed out executing POST問(wèn)題及解決方法,感興趣的朋友一起看看吧2024-01-01
idea如何快速查找一個(gè)類(lèi)或類(lèi)中方法名和變量
這篇文章主要介紹了idea如何快速查找一個(gè)類(lèi)或類(lèi)中方法名和變量問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
java對(duì)象與json對(duì)象之間互相轉(zhuǎn)換實(shí)現(xiàn)方法示例
這篇文章主要介紹了java對(duì)象與json對(duì)象之間互相轉(zhuǎn)換實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了java對(duì)象與json對(duì)象相互轉(zhuǎn)換實(shí)現(xiàn)步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
Java的List集合框架之LinkedList詳細(xì)解析
這篇文章主要介紹了Java的List集合框架之LinkedList詳細(xì)解析,LinkedList底層是內(nèi)部Node類(lèi)的存儲(chǔ),prev、next、item值,同時(shí)最外層還有first、last節(jié)點(diǎn),需要的朋友可以參考下2023-11-11
MyBatis開(kāi)啟二級(jí)緩存實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了MyBatis開(kāi)啟二級(jí)緩存實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
springboot使用JdbcTemplate完成對(duì)數(shù)據(jù)庫(kù)的增刪改查功能
這篇文章主要介紹了springboot使用JdbcTemplate完成對(duì)數(shù)據(jù)庫(kù)的增刪改查功能,需要的朋友可以參考下2017-12-12
Springboot MultipartFile文件上傳與下載的實(shí)現(xiàn)示例
在Spring Boot項(xiàng)目中,可以使用MultipartFile類(lèi)來(lái)處理文件上傳和下載操作,本文就詳細(xì)介紹了如何使用,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
java實(shí)現(xiàn)延遲/超時(shí)/定時(shí)問(wèn)題
這篇文章主要介紹了java實(shí)現(xiàn)延遲/超時(shí)/定時(shí)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04
關(guān)于LocalDateTime最常用方法和時(shí)間轉(zhuǎn)換方式
Java8版本引入了LocalDateTime和LocalDate類(lèi),極大地方便了日期和時(shí)間的處理,本文主要介紹了字符串與LocalDateTime的互轉(zhuǎn),Long型時(shí)間戳與UTC時(shí)間字符串的轉(zhuǎn)換,獲取今天、某天的起止時(shí)間,自定義時(shí)間的設(shè)置,以及LocalDateTime與Date的相互轉(zhuǎn)換等常用方法2024-11-11

