The examples in this article share with you the Java file upload technology for your reference. The specific content is as follows
Form:
The client must use the multipart/form-data data type to represent the composite data type when sending HTTP. Right now:
Use html tags in the form.
Package required:
Commons-fileupload.jar, the core upload file tool is in this package.
commons-io.jar package required to upload files
Detailed explanation of uploading file class:
DiskFileItemFactory - Create a time-monitoring file directory, which refers to the cache area size
ServletFileUpload is used to parse HttpServletRequest. Returns a set of file objects.
FileItem represents each file object uploaded by the user.
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>File upload demo</title> </head> <body> <font color="red" size="6">Transition board--understand the underlying layer</font> <!-- multipart/form-data: Multipart (not only files, but also parts) --> <form action="<%=request.getContextPath()%>/upload0" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"/> <input type="submit" value="upload"/> <!-- The uploaded file name cannot be in Chinese, otherwise the obtained file name is garbled, but the following example can solve this problem--> </form> <br/> <font color="red" size="6">Use the apache file upload tool to achieve file upload</font> <!-- application/x-www-form-urlencoded --> <form action="<%=request.getContextPath()%>/upload" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"/> <input type="submit" value="upload"/> </form> <font color="red" size="6">Use the apache file upload tool to achieve file upload 2 (solve the garbled file name)</font> <p> POST1 (normal form): enctype=application/x-www-form-urlencoded (default value) </p> <p> POST2 (upload file form): enctype=multipart/form-data:multipart (not only files, but also parts) </p> <form action="<%=request.getContextPath()%>/upload2" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"/><!-- POST2(upload file form) --><br/> File description:<input type="text" name="desc"/><!-- POST1(normal form) --><br/> File 2:<input type="file" name="file"/><br/> File description 2:<input type="text" name="desc"/><!-- POST1(normal form) --><br/> File 2:<input type="file" name="file"/><br/> File description 2:<input type="text" name="desc"/> <input type="submit" value="upload"/> </form> <font color="red" size="6">Use the apache file upload tool to achieve file upload 3 (file breakdown)</font> <!-- POST1 (normal form):enctype=application/x-www-form-urlencoded (default value) --> <!-- POST2 (upload file form):enctype=multipart/form-data:multipart (not only files, but also parts) --> <form action="<%=request.getContextPath()%>/upload3" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"/><!-- POST2 (upload file form) --><br/> File description:<input type="text" name="desc"/><!-- POST1 (normal form) --><br/><br/> File 2:<input type="file" name="file"/><br/> File description 2:<input type="text" name="desc"/> <input type="submit" value="upload"/> </form> </body></html>
Understanding the bottom layer of the transition board
package cn.hncu.servlet;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Upload0Servlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream in=request.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(in)); String line; while((line=br.readLine())!=null){ System.out.println(line); } }}Use the apache file upload tool to implement file upload
package cn.hncu.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print("Does not support Get uploading. . . . . . "); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //On the server, specify a directory for all uploaded files String path=getServletContext().getRealPath("/upload"); System.out.println("path:"+path); File dir=new File(path); if(!dir.exists()){ dir.mkdirs(); } //Create a hard disk-based factory//DiskFileItemFactory disk = new DiskFileItemFactory(); //Set temporary directory (it is recommended to design a temporary directory, otherwise the system temporary directory will be used.) //disk.setRepository(new File("d:/a")); //3. Set the buffer size for writing data to the hard disk disk.setSizeThreshold(1024*4); //When the file is larger than this setting, a temporary file will be formed in the temporary directory//Set the temporary file buffer size--8K buffer, temporary file address DiskFileItemFactory f=new DiskFileItemFactory(1024*8, new File("d:/a")); //Upload tool--create an object for parsing ServletFileUpload upload=new ServletFileUpload(f); upload.setFileSizeMax(1024*1024*5); //Set the maximum uploaded single file to 5M //Set the maximum size of the uploaded file. If it is multiple files, it is the sum of multiple files up to 8M upload.setSizeMax(1024*1024*8); //Set the sum of all uploaded file sizes up to 8M //Use the parsing tool to parse try { List<FileItem> list=upload.parseRequest(request); for(FileItem fI:list){ System.out.println("File Content Type:"+fI.getContentType());//File Content Type: text/plain System.out.println("File Name:"+fI.getName());//File Name: C:/Users/adl1/Desktop/a.txt String ext=fI.getName().substring(fI.getName().lastIndexOf("."));//.txt String uuid=UUID.randomUUID().toString().replace("-", ""); String fileName=uuid+ext;// FileUtils.copyInputStreamToFile(fI.getInputStream(), new File("d:/a/d/a.txt"));//Write it dead//fI.getInputStream() is the real file information FileUtils.copyInputStreamToFile(fI.getInputStream(), new File(path+"/"+fileName));//Write it alive} } catch (FileUploadException e) { e.printStackTrace(); } }} Store uploaded files in this place
Upload information:
Upload results:
Use the apache file upload tool to achieve file upload 2 (solve the garbled file name)
package cn.hncu.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;public class Upload2Servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //If it is a form containing uploaded files (POST2), the drama can only set the encoding in the file name of the uploaded file (solve its Chinese garbled code) //But it cannot solve the Chinese garbled code of ordinary form components in POST2 mode PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print("Does not support Get uploading. . . . . . "); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Step 1//Ordinary form form (POST1), the following sentence can set the encoding of the content of the ordinary form component (can solve their Chinese garbled problem) request.setCharacterEncoding("utf-8"); //If it is a form containing uploaded files (POST2), this sentence can only set the encoding in the file name of the uploaded file (solve its Chinese garbled code). But it cannot solve the garbled code of the ordinary form component (cannot set its encoding) //On the server, specify a directory for all uploaded files String path=getServletContext().getRealPath("/upload"); System.out.println("path:"+path); File dir=new File(path); if(!dir.exists()){ dir.mkdirs(); } //Set the temporary file buffer size--8K buffer, temporary file address DiskFileItemFactory f=new DiskFileItemFactory(1024*8, new File("d:/a")); //Upload tool ServletFileUpload upload=new ServletFileUpload(f); upload.setFileSizeMax(1024*1024*5); //Set the maximum uploaded single file to 5M upload.setSizeMax(1024*1024*8); //Set the sum of all uploaded file sizes to 8M //Use the parsing tool to parse try { List<FileItem> list=upload.parseRequest(request); for(FileItem fI:list){ if((fI.isFormField())){//If it is a normal form component: checkbox,radio,password...// String desc=fI.getString(); System.out.println("fI.getString():"+fI.getString()); //Second step String desc=fI.getString("utf-8"); //This sentence sets the content encoding of the ordinary form component System.out.println("After encoding:"+desc); }else{ String ext=fI.getName().substring(fI.getName().lastIndexOf("."));//.txt String uuid=UUID.randomUUID().toString().replace("-", ""); String fileName=uuid+ext; //fI.getInputStream() is the real file information FileUtils.copyInputStreamToFile(fI.getInputStream(), new File(path+"/"+fileName));//Write it alive} } } catch (FileUploadException e) { e.printStackTrace(); } }}Upload information:
Upload results:
Use the apache file upload tool to achieve file upload 3 (file breakdown)
Optimize file storage with the Hash directory:
The Hash directory is a method to optimize file storage performance. Whether it is Windows or Linux, whether it is NTFS or ext3, the number of items that can be accommodated in each directory is limited.
It is not that it cannot be saved, but when the number of projects is too large, the file indexing speed will be reduced.
Therefore, it is necessary to weigh how many files should be saved in a directory. Saving too much will affect performance, while saving too little will cause too many directories and waste of space. So when saving large batches of files,
There is an algorithm that can "break" files more evenly in different subdirectories to improve the index speed of each level. This algorithm is Hash. The commonly used MD5, sha1, etc. can be used as the Hash directory. MD5 is also used in my session to obtain the first and ninth digits of sessionID, which constitutes a two-level Hash path. That is to say, the system distributes all Session files to 16×16=256 subdirectories. Assuming that saving 1000 files in each directory of Linux can achieve the best space performance ratio, the system can ideally have 256,000 session files being used at the same time.
package cn.hncu.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;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.FileUploadException;import org.apache.commons.fileupload.ProgressListener;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;public class Upload3Servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //If it is a form containing uploaded files (POST2), the drama can only set the encoding in the file name of the uploaded file (solve its Chinese garbled code) //But it cannot solve the Chinese garbled code of ordinary form components in POST2 mode PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); //Get the part after the "?" number in the url in the GET method //http://localhost:8080/servletDemo3/upload?name=Jack&sex=male String qStr = request.getQueryString(); System.out.println("qStr: "+qStr);//qStr: name=Jack&sex=male out.print("Do not support Get upload. . . . . . "); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //1 Anti-black: The front-end of the protection is submitted using POST1 method //Method 1 /* String type=request.getContentType(); if(!type.contains("multipart/form-data")){ out.println("Non-supported form submission"); return; }*/ //Method 2 boolean boo = ServletFileUpload.isMultipartContent(request); if(!boo){ out.println("Non-supported form submission"); return; } //Step 1//Ordinary form form (POST1), the following sentence can set the encoding of the content of the ordinary form component (can solve their Chinese garbled problem) request.setCharacterEncoding("utf-8"); //If it is a form containing uploaded files (POST2), this sentence can only set the encoding in the file name of the uploaded file (solve its Chinese garbled code). But it cannot solve the garbled code of the ordinary form component (cannot set its encoding) //On the server, specify a directory for all uploaded files String path=getServletContext().getRealPath("/upload"); System.out.println("path:"+path); File dir=new File(path); if(!dir.exists()){ dir.mkdirs(); } //Set the temporary file buffer size--8K buffer, temporary file address DiskFileItemFactory f=new DiskFileItemFactory(1024*8, new File("d:/a")); //Upload tool ServletFileUpload upload=new ServletFileUpload(f); upload.setFileSizeMax(1024*1024*5); //Set the maximum uploaded single file to 5M upload.setSizeMax(1024*1024*8); //Set the maximum sum of all uploaded file sizes is 8M //▲4 Upload progress listening upload.setProgressListener(new ProgressListener(){ private double pre=0D; @Override//Parameter 1: How many bytes have been uploaded Parameter 2: How many bytes are total Parameter 3: Which file (serial number starts from 1) public void update(long pByteRead, long pContentLength, int pItems) { double d = 1.0*pByteRead/pContentLength*100; System.out.println(d+"%"); if(pre!=d){ System.out.println(d+"%"); pre=d; } } }); //Use parsing tool to parse try { List<FileItem> list=upload.parseRequest(request); for(FileItem fI:list){ if((fI.isFormField())){//If it is a normal form component: checkbox,radio,password...// String desc=fI.getString(); System.out.println("fI.getString():"+fI.getString()); //Second step String desc=fI.getString("utf-8"); //This sentence sets the content encoding of the normal form component System.out.println("encoding:"+desc); }else{ //Protect: Filter out empty file components that have not selected if(fI.getSize()<=0){ continue;//Read the next file} System.out.println("File content type:"+fI.getContentType());//File content type: text/plain System.out.println("File name:"+fI.getName());//File name: C:/Users/adl1/Desktop/a.txt String ext=fI.getName().substring(fI.getName().lastIndexOf("."));//.txt String uuid=UUID.randomUUID().toString().replace("-", ""); String fileName=uuid+ext; //File directory breaking technology String dir1=Integer.toHexString(uuid.hashCode()&0x0f); String dir2=Integer.toHexString((uuid.hashCode()&0xf0)>>4); //fI.getInputStream() is the real file information FileUtils.copyInputStreamToFile(fI.getInputStream(), new File(path+"/"+dir1+"/"+dir2+"/"+fileName));//Written alive} } } catch (FileUploadException e) { e.printStackTrace(); } }}Break the message:
Break the results:
File 1:
File 2:
Demonstrate the principle of upload progress
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.