The examples in this article share the file upload and download java implementation code for your reference. The specific content is as follows
front desk:
1. Submission method: post
2. There are file uploaded form items in the form: <input type="file" />
3. Specify the form type:
Default type: enctype="application/x-www-form-urlencoded"
File upload type: multipart/form-data
FileUpload
It is commonly used in the development of file upload function, and apache also provides file upload components!
FileUpload component:
1. Download the source code
2. Introduce jar files in the project
commons-fileupload-1.2.1.jar [File upload component core jar package]
commons-io-1.4.jar [Embroidery related tool classes for file processing]
use:
public class UploadServlet extends HttpServlet { // upload directory, save the uploaded resources public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /************ File upload component: Handle file upload*******************/ try { // 1. File upload factory FileItemFactory factory = new DiskFileItemFactory(); // 2. Create file upload core tool class ServletFileUpload upload = new ServletFileUpload(factory); // 1. Set the maximum size allowed for a single file: 30M upload.setFileSizeMax(30*1024*1024); // 2. Set the total size allowed for file upload form: 80M upload.setSizeMax(80*1024*1024); // 3. Set the encoding of the upload form file name// equivalent to: request.setCharacterEncoding("UTF-8"); upload.setHeaderEncoding("UTF-8"); // 3. Determine: Whether the current form is a file upload form if (upload.isMultipartContent(request)){ // 4. Convert the requested data into FileItem objects, and then encapsulate List<FileItem> list = upload.parseRequest(request); // traversal: Get each uploaded data for (FileItem item: list){ // Judgment: Normal text data if (item.isFormField()){ // Normal text data String fieldName = item.getFieldName(); // Form element name String content = item.getString(); // Form element name, corresponding data //item.getString("UTF-8"); Specify the encoding System.out.println(fieldName + " " + content); } // Upload file (file stream) ---> Upload to the upload directory else { // Normal text data String fieldName = item.getFieldName(); // Form element name String name = item.getName(); // File name String content = item.getString(); // Form element name, corresponding data String type = item.getContentType(); // File type InputStream in = item.getInputStream(); // Upload file stream/* * 4. File name is rename* For different users readme.txt files, do not want to be overwritten! * Background processing: Add a unique tag to the user! */ // a. Randomly generate a unique tag String id = UUID.randomUUID().toString(); // b. Splice name with file name = id +"#"+ name; // Get the upload base path String path = getServletContext().getRealPath("/upload"); // Create the target file File file = new File(path,name); // Tool class, file upload item.write(file); item.delete(); // Delete the temporary file generated by the system System.out.println(); } } } else { System.out.println("The current form is not a file upload form, processing failed!"); } } catch (Exception e) { e.printStackTrace(); } } // Manual implementation of the process private void upload(HttpServletRequest request) throws IOException, UnsupportedEncodingException { /* request.getParameter(""); // GET/POST request.getQueryString(); // Get the data submitted by GET request.getInputStream(); // Get the data submitted by post*/ /****************** Manually obtain file upload form data*************/ //1. Get form data stream InputStream in = request.getInputStream(); //2. Convert stream InputStreamReader inStream = new InputStreamReader(in, "UTF-8"); //3. BufferedReader reader = new BufferedReader(inStream); // Output data String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } // Output data String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } // Close reader.close(); inStream.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}Case:
Index.jsp
<body> <a href="${pageContext.request.contextPath }/upload.jsp">File Upload</a> <a href="${pageContext.request.contextPath }/fileServlet?method=downList">File Download</a> </body>Upload.jsp
<body> <form name="frm_test" action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data"> <%--<input type="hidden" name="method" value="upload">--%> Username: <input type="text" name="userName"> <br/> File: <input type="file" name="file_img"> <br/> <input type="submit" value="submit"> </form> </body>FileServlet.java
/** * Handle file upload and download* @author Jie.Yuan * */public class FileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get request parameters: distinguish different operation types String method = request.getParameter("method"); if ("upload".equals(method)) { // Upload upload(request,response); } else if ("downList".equals(method)) { // Enter the download list downList(request,response); } else if ("down".equals(method)) { // Download down(request,response); } } /** * 1. Upload */ private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1. Create factory object FileItemFactory factory = new DiskFileItemFactory(); // 2. File upload core tool class ServletFileUpload upload = new ServletFileUpload(factory); // Set size limit parameters upload.setFileSizeMax(10*1024*1024); // Single file size limit upload.setSizeMax(50*1024*1024); // Total file size limit upload.setHeaderEncoding("UTF-8"); // Processing Chinese file encoding// Judge if (upload.isMultipartContent(request)) { // 3. Convert request data to list collection List<FileItem> list = upload.parseRequest(request); // traversal for (FileItem item : list){ // Judgment: Normal text data if (item.isFormField()){ // Get the name String name = item.getFieldName(); // Get the value String value = item.getString(); System.out.println(value); } // File form item else { /************ File upload****************/ // a. Get the file name String name = item.getName(); // ---handle the problem of uploading file name duplicate name---- // a1. Get the unique mark String id = UUID.randomUUID().toString(); // a2. Splice file name name = id + "#" + name; // b. Get the upload directory String basePath = getServletContext().getRealPath("/upload"); // c. Create the file object to be uploaded File file = new File(basePath,name); // d. Upload item.write(file); item.delete(); // Delete the temporary file generated when the component is running} } } } } catch (Exception e) { e.printStackTrace(); } } /** * 2. Enter the download list*/ private void downList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Implementation idea: first get the file names of all files in the upload directory, and then save; jump to the down.jsp list to display //1. Initialize the map collection Map<file name containing unique tags, short file name> ; Map<String,String> fileNames = new HashMap<String,String>(); //2. Get the upload directory and the file names of all files under String bathPath = getServletContext().getRealPath("/upload"); // Directory File file = new File(bathPath); // In the directory, all file names String list[] = file.list(); // Traversal, encapsulate if (list != null && list.length > 0){ for (int i=0; i<list.length; i++){ // Full name String fileName = list[i]; // Short name String shortName = fileName.substring(fileName.lastIndexOf("#")+1); // Encapsulate fileNames.put(fileName, shortName); } } // 3. Save to request domain request.setAttribute("fileNames", fileNames); // 4. Forward request.getRequestDispatcher("/downlist.jsp").forward(request, response); } /** * 3. Handle download*/ private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the file name downloaded by the user (append data after the url address, get) String fileName = request.getParameter("fileName"); fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); // Get the upload directory path String basePath = getServletContext().getRealPath("/upload"); // Get a file stream InputStream in = new FileInputStream(new File(basePath,fileName)); // If the file name is Chinese, url encoding needs to be performed fileName = URLEncoder.encode(fileName, "UTF-8"); // Set the response header for download response.setHeader("content-disposition", "attachment;fileName=" + fileName); // Get response byte stream OutputStream out = response.getOutputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = in.read(b)) != -1){ out.write(b, 0, len); } // Close out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}The above is all about this article, I hope it will be helpful to everyone's learning.