SpringMVC (four) --- file upload and download

First, the file upload

File upload project development is one of the most common functions, springMVC can be a good support file uploads, but SpringMVC default context is not equipped MultipartResolver, therefore by default it can not handle file uploads work

If you want to use Spring file upload function, you need to configure MultipartResolver in context

1, the configuration file and the guide packet

For springmvc-servlet.xml profiling

1 <! - File Upload Configuration ->
 2      <the bean ID = "the MultipartResolver"
 . 3            class = "org.springframework.web.multipart.commons.CommonsMultipartResolver">
 . 4          <Property name = "defaultEncoding" value = "UTF-. 8 "/>
 5          <! - upload file size limit in bytes (= 10485760 1OM) ->
 . 6          <Property name =" maxUploadSize "value =" 1048576 "/>
 . 7          <Property name =" maxInMemorySize "value = "40960" />
 . 8      </ the bean>

2, the front end upload.jsp

In order to upload a file, the form must be set to POST method, and enctype to multipart / form-data; Only in this case, the browser will be selected by the user to the file server to send the binary data

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <body>
 4 
 5 <form action="${pageContext.request.contextPath}/upload1" 
 6                enctype="multipart/form-data" method="post">
 7     <p> 上传 文件:<input type="file" name="file"/></p>
 8     <p><input type="submit" value="上传"></p>
 9 </form>
10 
11 </body>
12 </html>

 

(1) by way stream of uploaded files

@RequestParam ( "file") the package name = file controls the resulting file into CommonsMultipartFile objects; arrays can be compared to bulk upload CommonsMultipartFile

CommonsMultipartFile common methods:

  • String getOriginalFilename (): Gets formerly known as uploading files
  • InputStream getInputStream (): Gets file stream
  • void transferTo (File dest): Save the file to upload a file directory

Code

. 1  @Controller
 2  public  class ControllerUpload {
 . 3  
. 4      @RequestMapping ( "/ upload1" )
 . 5      public String fileUpload (@RequestParam ( "File" ) CommonsMultipartFile File,
 . 6                                           the HttpServletRequest Request) throws IOException {
 . 7  
. 8          // 1. Get the name of the file 
9          uploadName = String file.getOriginalFilename ();
 10          // 2. If the file name is null is returned home 
. 11          IF ( "" .equals (uploadName)) {
 12 is              return "the redirect: /index.jsp";
 13 is          }
 14          System.out.println ( "upload file name:" + uploadName);
 15  
16          // 3. Upload path to save settings 
. 17          . Request.getServletContext String path = () the getRealPath ( "/ the WEB-INF / upload1 " );
 18          // 4. If a path does not exist is created 
. 19          File realpath = new new File (path);
 20 is          IF (! realPath.exists ()) {
 21 is              realPath.mkdir ();
 22 is          }
 23 is          the System.out. println ( "save path name:" + realpath);
 24  
25          // 5. the file input stream 
26         InputStream in = file.getInputStream();
27         //6.文件输入流
28         FileOutputStream out = new FileOutputStream(new File(realPath, uploadName));
29 
30         //7.读取
31         int len = 0;
32         byte[] bytes = new byte[1024];
33         while ((len = in.read(bytes)) != -1) {
34             out.write(bytes, 0, len);
35             out.flush();
36         }
37         out.close();
38         in.close();
39 
40         return "redirect:/success.jsp";
41     }
42 }

Run the test

Saved location

(2) the use of file.Transto to upload

Code

 1 @Controller
 2 public class ControllerUpload {
 3 
 4     @RequestMapping("/upload2")
 5     public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, 
 6                                        HttpServletRequest request) throws IOException {
 7 
 8         //上传路径保存设置
 9         String path = request.getServletContext().getRealPath("/WEB-INF/upload2");
10         File realPath = new File(path);
11         if (!realPath.exists()) {
12 is              realPath.mkdir ();
 13 is          }
 14  
15          // upload file address 
16          System.out.println ( "Upload File Save Address:" + realpath);
 . 17  
18 is          // write files directly by the method of CommonsMultipartFile (note that this time) 
. 19          file.transferTo ( new new File (realpath + "/" + file.getOriginalFilename ()));
 20 is  
21 is          return "the redirect: /success.jsp" ;
 22 is      }
 23 is }

[Note point: Here we have two ways to display a successful upload interface, the first one is like me, a successful new success .jsp;

Then after a successful upload to redirect to a successful interface. The second is to run JSON, plus @ResponseBody in the controller, and return a sentence, so after a successful upload will be displayed directly if you return]

Second, file download

1, the front download.jsp

 

1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <body>
4 
5 <a href="${pageContext.request.contextPath}/download">下载图片</a>
6 
7 </body>
8 </html>

 

2, controller codes

  1. Response in response to the first set
  2. Read a file - InputStream
  3. Write files - OutputStream
  4. Perform an operation
  5. Close stream (the first switch)
. 1  @Controller
 2  public  class ControllerDownload {
 . 3  
. 4      @RequestMapping ( "/ downloads" )
 . 5      public String Downloads (the HttpServletResponse Response) throws Exception {
 . 6  
. 7          // 1. address to download the image 
. 8          String path = "F.: \\ images " ;
 . 9          String fileName =" 9.jpg " ;
 10  
. 11          // 2. set response response header 
12 is          response.reset (); // set the page is not cached, empty buffer 
13 is          response.setCharacterEncoding (" UTF-. 8 "); // character encoding
14          the response.setContentType ( "multipart / form-Data"); // binary transmission data
 15          // 3. Set response header 
16          response.setHeader ( "the Content-Disposition" ,
 . 17                  "Attachment; fileName =" + the URLEncoder.encode ( fileName, "UTF-. 8" ));
 18 is  
. 19          file file = new new file (path, fileName);
 20 is          // 4. read the file - the input stream 
21 is          the InputStream iNPUT = new new the FileInputStream (file);
 22 is          // . 5. write file - output stream 
23 is          the OutputStream OUT = response.getOutputStream ();
 24  
25          byte[] buff =new byte[1024];
26         int index=0;
27         //6.执行 写出操作
28         while((index= input.read(buff))!= -1){
29             out.write(buff, 0, index);
30             out.flush();
31         }
32         out.close();
33         input.close();
34         return null;
35     }
36 }

Run the test

 

Guess you like

Origin www.cnblogs.com/tqsh/p/11297777.html