您好,登錄后才能下訂單哦!
本文實(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)存臨界值 - 超過后將產(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í)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。