π
Small
wood
come
Yes
\textcolor{Orange} {here comes Koki}
Here comes Koki
π£
holy
Birthday
tree
fire
Yes
\textcolor{green} {the Christmas tree is on fire}
The Christmas tree is on fire,
but
how
Do you
forget
Yes
writing
piece
upper
pass
And
\textcolor{red} {but why did you forget to upload the file}
But how did you forget to upload the file π£
π£
I
can
with
take
Promise
many
of
chart
slice
writing
files
etc.
all
can
with
enter
that 's ok
upper
pass
\textcolor{green} {I can upload many pictures and documents}
I can upload many pictures and documents
but
this
What
no
more
Cool
\textcolor{red} {but wouldn't it be better}
But wouldn't it be better π£
π
Bo
main
also
stay
learn
Learn
rank
paragraph
οΌ
as
if
hair
present
ask
topic
οΌ
please
Tell
know
οΌ
wrong
often
sense
thank
\textcolor{Orange} {blogger is also in the learning stage. If you find any problems, please let me know. Thank you very much}
Bloggers are also in the learning stage. If you find any problems, please let us know. Thank you very much π
Welcome to my friends π follow π give the thumbs-up β Collection π Leaving a message.
1. Principle and introduction of file transmission
2. Java web file upload
2.1 we create the project in a new way
An empty item will pop up directly
Set the jdk version
After clicking OK, it is relatively clean and won't do anything. Don't panic. Click file - > New - > module. Then it's the same as before
Create a model: file and configure tomcat to run without errors
2.2 Guide Package
You can choose to go to the maven warehouse, or search it on the official website and copy it to the project. We create a folder lib, and then right-click add as library to add it to the internal library if it is copied to the project from the outside
- The above is just about the way to create a new project. I will finish a project with maven as before
2.3 introduction to practical class
- Precautions for file upload
- In order to ensure the security of the server, the uploaded files should be placed in a directory that cannot be directly accessed by the outside world, such as the WEB-INF directory.
- To prevent file overwriting, a unique file name should be generated for the uploaded file,
- Add a timestamp
- UUID
- md5
- Self writing bit operation algorithm
- To limit the maximum number of uploaded files
- You can limit the type of uploaded file and judge whether the suffix is legal when you receive the uploaded file name.
Detailed explanation of classes to be used
ServletFileUpload is responsible for processing the uploaded file data and sealing each input item in the form into a fileItem object. The DiskFileItemFactory object is required when using the ServletFileUpload object to parse the request. Therefore, we need to construct the DiskFileItemFactory object before parsing, and set the fileItemFactory property of the ServletFileUpload object through the construction method of the ServletFileUpload object or the setFileItemFactory() method.
FileItem class
input in HTML page must have
<input type="file" name = "filename">
If the form contains a file upload input item, the enctype attribute of the form must be set to multipart / form data
- Introduction to common methods
//The isFromField method is used to judge whether the data encapsulated by the FileItem class object is an ordinary text form or a file form. If it is an ordinary form, it returns true; otherwise, it returns false boolean isFormField(); //The getFieldName method is used to return the value of the name property of the form label String getFieldName(); //The getString method is used to return the data stream content saved in the FileItem object as a string String getString(); //The getName method is used to obtain the file name in the file upload field String getName(); //Return the data content of the uploaded file in the form of stream InputStream getInputStream(); //The delete method is used to empty the body content stored in the FileItem class object. If the topic content is saved in a temporary file, the delete method deletes the temporary file void delete();
ServletFileUpload class
ServletFileUpload is responsible for processing the uploaded file data, and encapsulating each input item in the form into a fileitem object. Using its parseRequest(HttpServletRequest) method, the data submitted through each HTML tag in the form can be encapsulated into a fileitem object, and then returned in the form of list. Using this method to process uploaded files is simple and easy to use
2.4 pom. Dependencies required for XML import
<!--Servlet rely on--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--JSP rely on--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2.5 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--Upload file via form; get: Upload file size is limited post: There is no limit on the size of uploaded files ${pageContext.request.contextPath}Get the current path of the server --%> <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post"> Upload user:<input type="text" name="username"><br/> <p><input type="file" name="file1"></p> <p><input type="file" name="file1"></p> <p><input type="submit"> | <input type="reset"></p> </form> </body> </html>
2.6 info.jsp
This page is mainly used to accept message s
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%=request.getAttribute("msg")%> </body> </html>
2.7 FileServlet
Be careful not to misdirect the bags here. In addition, the encapsulation method is used here to make the structure look more concise
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 javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.UUID; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Determine whether the uploaded file is an ordinary form or a form with a file if (!ServletFileUpload.isMultipartContent(req)) { return;//The termination method runs, indicating that this is an ordinary form } //Create the save path of the uploaded file. It is recommended that it be safe under the WEB-INF path. Users cannot directly access the uploaded file //Get global context, address String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdir();//Create this directory } //Cache, temporary file //Temporary file. If the file exceeds the expected size, we will put it into a temporary file and delete it in a few days, or remind the user to save it permanently String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdir();//Create this directory } //To process the uploaded files, we usually need to obtain them through the stream. We can use request Getinputstream(), the original file upload stream, //The above is too troublesome. It is recommended to use APache's file upload component to implement common file upload, which depends on the common IO component try { //1. Create a DiskFileItemFactory object to handle file upload path or size restrictions DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile); //2. Get ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //3. Process uploaded files String msg = uploadParseRequest(upload, req, uploadPath); //servlet request forwarding message req.setAttribute("msg", msg); req.getRequestDispatcher("info.jsp").forward(req, resp); } catch (FileUploadException e) { e.printStackTrace(); } } public static DiskFileItemFactory getDiskFileItemFactory(File tmpFile) { DiskFileItemFactory factory = new DiskFileItemFactory(); //Set a buffer through the factory. When the uploaded file is larger than the buffer, it will be put into the temporary file //It can be set or not factory.setSizeThreshold(1024 * 1024); factory.setRepository(tmpFile); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) { //2. Get ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); //Can be set, can not be set //Monitor file upload progress upload.setProgressListener(new ProgressListener() { //pContentLength: file size //pBytesRead: the size of the file that has been read @Override public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("Total size:" + pContentLength + "Uploaded" + pBytesRead); } }); //Dealing with garbled code upload.setHeaderEncoding("UTF-8"); //Sets the maximum value for a single file upload.setFileSizeMax(1024 * 1024 * 10); //Set the total size of files that can be uploaded //1024 = 1kb * 1024 = 1M * 10 = 10M upload.setSizeMax(1024 * 1024 * 10); return upload; } public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException { String msg = ""; //3. Process uploaded files //The front-end request is parsed and encapsulated into a FileItem object, which needs to be obtained from the ServletFileUpload object List<FileItem> fileItems = upload.parseRequest(req); //Each form object for (FileItem fileItem : fileItems) { //Determine whether the uploaded file is an ordinary form or a form with a file if (fileItem.isFormField()) { //getFieldName() refers to the name of the front-end form control String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8");//Deal with garbled code System.out.println(name + ":" + value); } else { //Status of documents //=====Processing files //Get the file name String uploadFileName = fileItem.getName(); System.out.println("Uploaded file name:" + uploadFileName); if (uploadFileName.trim().equals("") || uploadFileName == null) { continue; } //Obtain the file name and suffix of file upload/ images/boys/dajie.jpg the following is not necessary String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1); //If the file suffix fileExtName is not what we need, we can directly return, do not process it, and tell the user that the file type is wrong System.out.println("File information [file name:" + fileName + "---file type" + fileExtName + "]"); //You can use UUID (universal code for unique identification) to ensure that the file name is unique //UUID.randomUUID() randomly generates a unique universal code //Everything in network transmission needs to be serialized, //For example: POJO, entity class, if you want to run on multiple computers, you need to transfer = = = > you need to serialize the object //implements Serializable: tag interface, JVM -- > java stack, local method stack; native--->C++ String uuidPath = UUID.randomUUID().toString(); //===End of processing file //=====Storage address //Where? uploadPath //The real path of the file realPath String realPath = uploadPath + "/" + uuidPath; //Create a folder for each file File realPathFile = new File(realPath); if (!realPathFile.exists()) { realPathFile.mkdir(); } //=====Storage address completed //=====File transfer //Get the stream of file upload InputStream inputStream = fileItem.getInputStream(); //Create a file output stream //realPath = real folder //One file is missing, plus the name of the output file + "/" + uuidFileName FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); //Create a buffer byte[] buffer = new byte[1024 * 1024]; //Judge whether the reading is completed int len = 0; //If it is greater than 0, data still exists while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } //Close flow fos.close(); inputStream.close(); msg = "File upload succeeded!"; fileItem.delete();//Upload successful, clear temporary file } } return msg; } }
2.8 configuring servlets
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>com.hxl.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping> </web-app>
2.9 test results
3. Spring MVC file upload and download
3.1 upload
There are two ways in the controller
Create a new module and a set of processes as a whole. The test can run
β β > guide enter j a r package \Textcolor {orangered} {-- > Import jar package} − − > Import jar package π»
<!--File upload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
β β > i n d e x . j s p \textcolor{OrangeRed}{--> index.jsp} ββ>index.jspπ»
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>File upload and download</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form> </body> </html>
β β > a p p l i c a t i o n C o n t e x t . x m l in match Set b e a n \Textcolor {orangered} {-- > configure bean s in applicationcontext.xml} −−>applicationContext. Configuring bean s in XML π»
<!--File upload configuration--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- The encoding format of the request must be and jSP of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- Maximum upload file size, in bytes (10485760)=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
β β > F i l e C o n t r o l l e r \textcolor{OrangeRed}{--> FileController} ββ>FileControllerπ»
package com.hxl.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @RestController public class FileController { //@RequestParam("file") encapsulates the file obtained by the name=file control into a CommonsMultipartFile object //If you upload CommonsMultipartFile in batch, it can be an array @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { //Get file name: file getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //If the file name is empty, go back to the home page directly! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("Upload file name : "+uploadFileName); //Upload path save settings String path = request.getServletContext().getRealPath("/upload"); //If the path does not exist, create one File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("Upload file storage address:"+realPath); InputStream is = file.getInputStream(); //File input stream OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //File output stream //Read write int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } /* * Use file To save the uploaded file */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //Upload path save settings String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //Upload file address System.out.println("Upload file storage address:"+realPath); //Write the file directly through the CommonsMultipartFile method (note this time) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; } }
β β > measure try : \Textcolor {orangered} {-- > test:} − − > test: π»
3.2 download
1. Set response header
2. Read file – InputStream
3. Write out file – OutputStream
4. Perform operation
5. Close flow (first on then off)
β β > i n d e x . j s p \textcolor{OrangeRed}{--> index.jsp} ββ>index.jspπ»
<a href="${pageContext.request.contextPath}/download">Click download</a>
β β > increase plus one individual u p l o a d writing piece \Textcolor {orangered} {-- > add an upload file} − − > add an upload file π»
And get in the pictures to download
β β > c o n t r o l l e r \textcolor{OrangeRed}{-->controller} ββ>controllerπ»
@RequestMapping(value="/download") public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{ //Address of the picture to download String path = request.getServletContext().getRealPath("/upload"); //String filename = "the file you want to download should be suffixed"; String fileName = "1.jpg"; //1. Set response header response.reset(); //Set the page not to be cached, and clear the buffer response.setCharacterEncoding("UTF-8"); //Character encoding response.setContentType("multipart/form-data"); //Binary transmission data //Set response header response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2. Read file -- input stream InputStream input=new FileInputStream(file); //3. Write out file -- output stream OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4. Perform a write out operation while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return "ok"; }
β β > measure try : \Textcolor {orangered} {-- > test:} − − > test: π»