1, File upload
Dependent jar packages:
comments-fileupload.jar comments-io.jar
1. Form attribute enctype = "multipart / form data" method = "post";
2. Request code and response code settings;
3. 3 steps to parse request object
Create factory class: FileItemFactory factory=DisFileItemFactory();
Create parser: servletfileupload = new servletfileupload (factory);
Use the parser to parse the request object: List < fileitem > items = upload parseRequest(request);
4. Restriction element (before parser parsing)
①upload.setFileSizeMax(1024*n); Limit the size of all file uploads
②upload.setSizeMax(1024*n); Limit the size of a single file upload
③upload.setHeaderEncoding("utf-8"); Set the uploaded Chinese format
5. FileItem object related methods
①String itemName = item.getFieldName() ; Gets the name value of the form item
②boolean isFormField() ; Judge whether it is an ordinary form field (true/false) -- that is, the difference between ordinary fields such as text and file
③ String getString("code setting"); Get field content, normal field -- value value file field -- file content
④ String getContextType(): gets the upload file type text/image. If it is a normal field, null will be returned. You can also limit the upload file type through the suffix in the file name string;
⑥ long getSize(1024*n): get the field content size, in byte s
⑦ InputStream getInputStream(): get the input stream of the file content. If it is a normal field, return the input value of value
6. Get form data (text, file...)
① Define receive variables
② Iterator / for loop variable item value
Items usage: items Next() returns boolean
whie(items.next()){
FileItem item = items.next();
String itemName = item.getFieldName();// Get name
var var = -1/null/...
if(item.isFormField()){
if(equals name){
var = item.getString("utf-8");// Accept value matching name
}else if(...){
...
}eles{
Other fields
}
}else{
String fileName = item.getName(); Get file name
File related operations
}
}
7. File related operations
(1) Get path string
①String path = "xxxx"; / / specify the path statically
②String path = request.getSession().getServletContext().getRealPath("upload") / / dynamically obtain the project path under tomcat
③ File dir = new File("path + project name (" d:/upload ")")// Create your own directory
if(!dir.exists()){
dir.mkdirs(); // Create if not present
}
(2) Get file name (including suffix)
String fileName = item.getName();
Handle the overwriting problem caused by file name duplication - UUID class
UUID uuid = UUID.randomUUID();
String uuidName = uuid.toString()+fileName.substring(fileName.lastIndexOf("."));
③ How to store files (path location and file name)
File file = new file path: path/dir file name: fileName/uuidName;
④ File upload (item is actually the file content obtained)
item.write(file);
Simple example:
<form action="uploadServlet" enctype="multipart/form-data" method="post"> Document number:<input type="text" name="fno"/> file:<input type="file" name="file"/> </form>
//Set encoding format request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=UTF-8"); Iterator<FileItem> iter = items.iterator();// List elements via iterators while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { // type = form attribute String itemName = item.getFieldName(); String fno = ""; if (itemName.equals("fno")) { fno = item.getString();//Get the attribute value with name fno System.out.println("fno Attribute value:" + fno); } else { System.out.println("Other attribute fields..."); } } else { // type=file System.out.println("xxx"); String fileName = item.getName();// Get file name File dir = new File("D:/testDir");// File storage directory, create if none if (!(dir.exists())) { dir.mkdirs(); } File file = new File(dir, fileName); item.write(file); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { // Not a file form System.out.println("Non file form..."); }
2, File download
Dependent jar package: None
1. Download the file through < a href = "" > < / a > or form form - get the download file name
<form action="downloadServlet" method="post"> file name:<input type="text" name="fname"/><br> <input type="submit" value="download"/><br> </form> <a href="downloadServlet?fname=1234.docx">The download file name is 1234.docx File</a>
2. Configure the response header in the downloadServlet
response.addHeader("content-Type", "application/octet-stream"); response.addHeader("content-Disposition", "attachment;filename=" + fname);
Garbled file names downloaded by different browsers:
However, I tested it, even if it is set to urlencoder Encode (fname, "UTF-8"), and it will not be garbled when downloaded on Firefox.
String agent = request.getHeader("User-Agent"); if (agent.toLowerCase().indexOf("firefox") != -1) { System.out.println("Firefox settings"); response.addHeader("content-Disposition", "attachment;filename==?UTF-8?B?" + new String(Base64.encodeBase64(fname.getBytes("utf-8")) + "?=")); } else { System.out.println("Non Firefox settings:" + agent); response.addHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "utf-8")); }
3. Gets the path to the downloaded file
String path = "D:/testDir/" + fname;
4. Convert files to input / output streams through IO operations
InputStream in = new FileInputStream(path);//Convert the corresponding directory file into an input stream /* * The file is in the project directory * InputStream in = getServletContext().getResourceAsStream("/ServletDir/" + fname); */ ServletOutputStream out = response.getOutputStream(); byte[] chs = new byte[100]; int len = -1; while ((len = in.read(chs)) != -1) { out.write(chs, 0, len); } //Close flow out.close(); in.close();
Simple example:
<form action="downloadServlet" method="post"> file name:<input type="text" name="fname"/><br> <input type="submit" value="download"/><br> </form> <a href="downloadServlet?fname=1234.docx">The download file name is 1234.docx File</a>
// Response header String fname = request.getParameter("fname"); response.addHeader("content-Type", "application/octet-stream"); // response.addHeader("content-Disposition", "attachment;filename=" + fname); String agent = request.getHeader("User-Agent"); if (agent.toLowerCase().indexOf("firefox") != -1) { System.out.println("Firefox settings"); response.addHeader("content-Disposition", "attachment;filename==?UTF-8?B?" + new String(Base64.encodeBase64(file.getFname().getBytes("utf-8")) + "?=")); } else { System.out.println("Non Firefox settings:" + agent); response.addHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "utf-8")); } String path = "D:/testDir/" + fname; System.out.println(path); InputStream in = new FileInputStream(path); // InputStream in = getServletContext().getResourceAsStream("/ServletDir/"+fname); // OutputStream out = new FileOutputStream(); ServletOutputStream out = response.getOutputStream(); byte[] chs = new byte[100]; int len = -1; while ((len = in.read(chs)) != -1) { out.write(chs, 0, len); } out.close(); in.close();