您好,登錄后才能下訂單哦!
本文實例為大家分享了java實現文件上傳下載的具體代碼,供大家參考,具體內容如下
一.上傳
1.前端:
<form method="post" action="FileUpload" enctype="multipart/form-data"> <input type="file" name="uploadFile" /> <br/> <input type="submit" value="上傳" /> </form>
2.后臺:
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; } // 配置上傳參數 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置內存臨界值 - 超過后將產生臨時文件并存儲于臨時目錄中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 設置臨時存儲目錄 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 設置最大文件上傳值 upload.setFileSizeMax(MAX_FILE_SIZE); // 設置最大請求值 (包含文件和表單數據) 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 { // 解析請求的內容提取文件數據 List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 迭代表單數據 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); // 在控制臺輸出文件的上傳路徑 // 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") --------- 需要對URL中的中文參數進行編碼,否則會出現亂碼
2.后臺:
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"); //需要對URL中的中文參數進行編碼,否則出現亂碼 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); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。