The recently learned file upload in the web phase, I just want to record it, help myself review and help you learn. Generally, I will save the uploaded file under the web inf in the server, because the user will not directly access it, and the path we save to the database is generally the path. There is no demonstration of database upload path. Momentum upload path is very simple. You only need to insert the path and file name into a table in the database. When you want to find the file, you can find the path from the database. Needless to say, the upper code (for the servlet that uploads files, the foreground interface only needs to have an input tag of file type. If you want to select multiple uploads at one time, you can write more input or add multiple="multiple" attribute in the input tag, then you can write several files in one input):
1 package practice;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.UnsupportedEncodingException;
8 import java.util.List;
9 import java.util.UUID;
10
11 import javax.servlet.ServletException;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 import org.apache.commons.fileupload.FileItem;
17 import org.apache.commons.fileupload.FileUploadBase;
18 import org.apache.commons.fileupload.FileUploadException;
19 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
20 import org.apache.commons.fileupload.servlet.ServletFileUpload;
21 import org.apache.commons.io.FilenameUtils;
22
23
24
25 public class UploadServlet extends HttpServlet {
26
27 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
28 //Determine whether the form upload method is multipart/form-data;
29 boolean ismultipartContent = ServletFileUpload.isMultipartContent(request);
30 if(!ismultipartContent){
31 throw new RuntimeException("your form is not multipart/form-data");
32 }
33 //Create a DiskFileItemFactory Factory
34 DiskFileItemFactory factory = new DiskFileItemFactory();
35 //Create a directory for temporary file storage
36 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
37 File tempFile = new File(tempPath);
38 if(!tempFile.exists()){
39 tempFile.mkdir();
40 }
41 factory.setRepository(tempFile);
42 //Establish ServletFileUoload Core objects
43 ServletFileUpload sfu = new ServletFileUpload(factory);
44 //Solve the problem of file upload garbled
45 sfu.setHeaderEncoding("utf-8");
46 try {
47 sfu.setFileSizeMax(1024*1024*3); //Single file size
48 sfu.setSizeMax(1024*1024*6); //Total file size
49 //Traversing the form collection returns a List<FileItem>aggregate
50 List<FileItem> fileItems = sfu.parseRequest(request);
51 for(FileItem fileItem:fileItems){
52 //Determine whether it is a normal form or an upload form
53 if(fileItem.isFormField()){
54 //Process as normal form
55 processFormField(fileItem);
56 }else{
57 //Process according to the upload form
58 processUploadField(fileItem);
59 }
60 }
61 }catch(FileUploadBase.FileSizeLimitExceededException e){
62 e.printStackTrace();
63 request.setAttribute("message", "Single file exceeds maximum");
64 request.getRequestDispatcher("/uploadSong.jsp").forward(request, response);
65 return;
66 }catch(FileUploadBase.SizeLimitExceededException e){
67 e.printStackTrace();
68 request.setAttribute("message", "The total size of the uploaded file exceeds the limit");
69 request.getRequestDispatcher("/uploadSong.jsp").forward(request, response);
70 return;
71 }
72 catch (FileUploadException e) {
73 // TODO Auto-generated catch block
74 e.printStackTrace();
75 } //Traverse form item collection
76
77
78 }
79
80
81
82 //Functions for handling uploaded files
83 private void processUploadField(FileItem fileItem) {
84 //Get the name of the uploaded file
85 String filename = fileItem.getName();
86 //Get file input stream
87 try {
88 InputStream is = fileItem.getInputStream();
89 //Save file on server
90 String directoryRealPath =this.getServletContext().getRealPath("/WEB-INF/upload");//Path created
91 File storeDirectory = new File(directoryRealPath);
92 if(!storeDirectory.exists()){
93 storeDirectory.mkdir(); //Create a specified directory
94 }
95 //Process filename
96 //filename =filename.substring(filename.lastIndexOf(File.separator)+1);
97 if(filename!=null){
98 filename=FilenameUtils.getName(filename);
99 }
100 //Do not duplicate file names
101 filename=UUID.randomUUID()+"_"+filename;
102 //Break up the catalogue
103 String childDirectory = makChildDirectory(storeDirectory,filename);
104
105 //Build a complete file path
106 /*File file =new File(storeDirectory,childDirectory+File.separator+filename);
107 //Create a write stream and write the picture to the path
108 FileOutputStream fos = new FileOutputStream(file);
109 int len=0;
110 byte [] buf = new byte[1024];
111 while((len=is.read(buf))!=-1){
112 fos.write(buf,0,len);
113 }
114 fos.close();
115 is.close();*/
116 //Using tool class to upload files
117 fileItem.write(new File(storeDirectory,childDirectory+File.separator+filename));
118 fileItem.delete();//Delete temporary files
119 } catch (Exception e) {
120 // TODO Auto-generated catch block
121 e.printStackTrace();
122 }
123 }
124
125
126 //Break up the catalogue
127 private String makChildDirectory(File storeDirectory, String filename) {
128 int hashcode = filename.hashCode();
129 //hold hashcode Convert to hex
130 String code = Integer.toHexString(hashcode);
131 String childDirectory = code.charAt(0)+File.separator+code.charAt(1);
132 File file = new File(storeDirectory,childDirectory);
133 if(!file.exists()){
134 file.mkdirs();
135 }
136 return childDirectory;
137 }
138
139
140
141 //Functions for handling normal forms
142 private void processFormField(FileItem fileItem) {
143 //Solve the problem of file name scrambling
144 try {
145 String fieldName = fileItem.getFieldName(); //Get field name
146 //String fieldValue = fileItem.getString(); //Get value
147 String fieldValue = fileItem.getString("utf-8");
148 } catch (UnsupportedEncodingException e) {
149 // TODO Auto-generated catch block
150 e.printStackTrace();
151 }
152 }
153
154
155
156
157 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
158
159 doGet(request, response);
160 }
161
162 }