In the development of web application system, file upload and download functions are very commonly used functions. Today, let’s talk about the implementation of file upload and download functions in JavaWeb.
1. Upload a simple example
Jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>File Upload and Download</title></head><body><form action="${pageContext.request.contextPath}/UploadServlet" enctype="multipart/form-data" method="post"> Upload user: <input type="text" name="username" /> <br /> Upload file 1: <input type="file" name="file1" /> <br /> Upload file 2: <input type="file" name="file2" /> <br /> <input type="submit" value="upload"/></form> <br />${requestScope.message}</body></html>Servlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ //1. Get the parser factory DiskFileItemFactory factory = new DiskFileItemFactory(); //2. Get the parser ServletFileUpload upload = new ServletFileUpload(factory); //3. Determine the type of uploading form if(!upload.isMultipartContent(request)){ // Upload the form is a normal form, then obtain the data in the traditional way and return; } //To upload a form, the parser is called to parse the upload data List<FileItem> list = upload.parseRequest(request); //FileItem //Transipulate the list to obtain the first upload input item data fileItem object for(FileItem item : list){ if(item.isFormField()){ //What you get is the normal input item String name = item.getFieldName(); //Get the name of the input item String value = item.getString(); System.out.println(name + "=" + value); }else{ //Get the upload input item String filename = item.getName(); //Get uploaded file name C:/Documents and Settings/ThinkPad/Desktop/1.txt filename = filename.substring(filename.lastIndexOf("//")+1); InputStream in = item.getInputStream(); //Get uploaded data int len = 0; byte buffer[]= new byte[1024]; //The directory used to save uploaded files should prohibit the outside world from directly accessing String savepath = this.getServletContext().getRealPath("/WEB-INF/upload"); System.out.println(savepath); FileOutputStream out = new FileOutputStream(savepath + "/" + filename); //Write file to the upload directory while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); request.setAttribute("message", "upload success"); } } } } catch (Exception e) { request.setAttribute("message", "upload failed"); e.printStackTrace(); } }2. Modified upload function:
Notes:
1. Chinese garbled code for uploading file names and Chinese garbled code for uploading data
upload.setHeaderEncoding("UTF-8"); //Solve Chinese garbled code for uploading file names
//The form is uploaded for file, the request encoding is invalid, and can only be converted manually
1.1 value = new String(value.getBytes("iso8859-1"),"UTF-8");
1.2 String value = item.getString("UTF-8");
2. To ensure the security of the server, upload files should be placed in directories that cannot be directly accessed by the outside world.
3. To prevent file overwriting, a unique file name must be generated for uploading the file.
4. To prevent too many files from appearing under a directory, you need to use the hash algorithm to break up the storage.
5. To limit the maximum value of uploaded files, you can use the: ServletFileUpload.setFileSizeMax(1024) method and capture:
FileUploadBase.FileSizeLimitExceededException exception to give user-friendly prompts
6. If you want to ensure that the temporary file is deleted, you must call the item.delete method after processing the upload file.
7. To limit the type of uploaded file: When receiving the uploaded file name, determine whether the suffix name is legal.
8. Listen to file upload progress:
ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("File size is: " + pContentLength + ", currently processed: " + pBytesRead); } }); 9. Dynamically add file upload input items in the web page
function addinput(){ var div = document.getElementById("file"); var input = document.createElement("input"); input.type="file"; input.name="filename"; var del = document.createElement("input"); del.type="button"; del.value="Delete"; del.onclick = function d(){ this.parentNode.parentNode.removeChild(this.parentNode); } var innerdiv = document.createElement("div"); innerdiv.appendChild(input); innerdiv.appendChild(del); div.appendChild(innerdiv); }Upload jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>My JSP 'upload2.jsp' starting page</title> <script type="text/javascript"> function addinput(){ var div = document.getElementById("file"); var input = document.createElement("input"); input.type="file"; input.name="filename"; var del = document.createElement("input"); del.type="button"; del.value="delete"; del.onclick = function d(){ this.parentNode.parentNode.removeChild(this.parentNode); } var innerdiv = document.createElement("div"); innerdiv.appendChild(input); innerdiv.appendChild(del); div.appendChild(innerdiv); } </script> </head> <body> <form action="" enctype="mutlipart/form-data"></form> <table> <tr> <td>Upload user: </td> <td><input type="text" name="username"></td> </tr> <tr> <td>Upload file: </td> <td> <input type="button" value="Add upload file" onclick="addinput()"> </td> </tr> <tr> <td></td> <td> <div id="file"> </div> </td> </td> </tr> </table> </body></html>Upload servlet
public class UploadServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request.getParameter("username"); //**** Error request.setCharacterEncoding("UTF-8"); //The form is uploaded for file, and the request encoding is invalid//Get the uploaded file savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); try{ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp"))); ServletFileUpload upload = new ServletFileUpload(factory); /*upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("File size is: " + pContentLength + ", currently processed: " + pBytesRead); } });*/ upload.setHeaderEncoding("UTF-8"); //Solve the Chinese garbled code of uploading file names if(!upload.isMultipartContent(request)){ //Get data in traditional way return; } /*upload.setFileSizeMax(1024); upload.setSizeMax(1024*10);*/ List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ if(item.isFormField()){ //The data of ordinary input items are encapsulated in the fileitem String name = item.getFieldName(); String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{ //The upload file is encapsulated in the fileitem String filename = item.getName(); //The files submitted by different browsers are different c:/a/b/1.txt 1.txt System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } filename = filename.substring(filename.lastIndexOf("//")+1); InputStream in = item.getInputStream(); String saveFilename = makeFileName(filename); //Get the name of the file saved String realSavePath = makePath(saveFilename, savePath); //Get the file save directory FileOutputStream out = new FileOutputStream(realSavePath + "//" + saveFilename); byte buffer[] = new byte[1024]; int len = 0; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); item.delete(); //Delete temporary file} } } catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "The file exceeds the maximum value! ! ! "); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } catch (Exception e) { e.printStackTrace(); } } public String makeFileName(String filename){ //2.jpg return UUID.randomUUID().toString() + "_" + filename; } public String makePath(String filename,String savePath){ int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 String dir = savePath + "//" + dir1 + "//" + dir2; //upload/2/3 upload/3/5 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}3. Download function
//List all download files on the website public class ListFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filepath = this.getServletContext().getRealPath("/WEB-INF/upload"); Map map = new HashMap(); listfile(new File(filepath),map); request.setAttribute("map", map); request.getRequestDispatcher("/listfile.jsp").forward(request, response); } public void listfile(File file,Map map){ if(!file.isFile()){ File files[] = file.listFiles(); for(File f : files){ listfile(f,map); } }else{ String realname = file.getName().substring(file.getName().indexOf("_")+1); //9349249849-88343-8344_A_Fan_Davi.avi map.put(file.getName(), realname); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}jsp display
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>My JSP 'listfile.jsp' starting page</title> </head> <body> <c:forEach var="me" items="${map}"> <c:url value="/servlet/DownLoadServlet" var="downurl"> <c:param name="filename" value="${me.key}"></c:param> </c:url> ${me.value } <a href="${downurl}">Download</a> <br/> </c:forEach> </body></html>Download processing servlet
public class DownLoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); //23239283-92489-Avatar.avi filename = new String(filename.getBytes("iso8859-1"),"UTF-8"); String path = makePath(filename,this.getServletContext().getRealPath("/WEB-INF/upload")); File file = new File(path + "//" + filename); if(!file.exists()){ request.setAttribute("message", "The resource you want to download has been deleted!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } String realname = filename.substring(filename.indexOf("_")+1); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); FileInputStream in = new FileInputStream(path + "//" + filename); OutputStream out = response.getOutputStream(); byte buffer[] = new byte[1024]; int len = 0; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); } public String makePath(String filename,String savePath){ int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 String dir = savePath + "//" + dir1 + "//" + dir2; //upload/2/3 upload/3/5 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.