The download of files and the uploading of files is an important function point in Web applications. This "Spingmvc file download" is based on the previously written "SPRINGMVC implementation File Upload " written, so here does not start from scratch to build a test project, directly followed the last project to test, So before you read this article, you need to go through the last article.
Note: SPRINGMVC implementation file upload:http://www.zifangsky.cn/406.html
(1) In the upload method of Uploadcontroller.java This controller, add the filename of the file that returned the upload:
Modelandview.addobject ("Picname", TargetFileName);
Once added, the complete code for this method is as follows:
@RequestMapping (value = "/upload", method = requestmethod.post) public Modelandview upload (user user, @RequestParam ("file") MultipartFile tmpFile, Httpservletrequest request) {modelandview modelandview = new modelandview (" FileUpload ");if (tmpfile != null) {// Get physical path string targetdirectory = Request.getsession (). Getservletcontext (). Getrealpath ("/uploads"); String tmpfilename = tmpfile.getoriginalfilename (); // uploaded file name int dot = tmpfilename.lastindexof ('. '); string ext = ""; // file suffix name if (dot > -1) && (dot < (Tmpfilename.length () - 1)) {ext = tmpfilename.substring (dot + &NBSP;1);} Other file formats do not process if ("PNG". Equalsignorecase (EXT) | | "JPG". Equalsignorecase (EXT) | | "GIF". Equalsignorecase (EXT)) &NBSP;{//&NBSP; Rename the uploaded file name string targetfilename = stringutile.renamefilename (tmpfilename);// saved new files target = new file (Targetdirectory, targetfilename);try {// Save File Fileutils.copyinputstreamtofile (Tmpfile.getinputstream (), target);} catch (ioexception e) {e.printstacktrace ();} User u = new user (); U.setusername (User.getusername ()); U.setlogosrc (Request.getContextPath ( ) + "/uploads/" + targetfilename); Modelandview.addobject ("U", u); Modelandview.addobject ("Picname", targetfilename);} Return modelandview;} Return modelandview;}
(2) Add a hyperlink to a file download in the fileupload.jsp file:
that is assigned by the "Picname" in the controller.650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/85/83/wKioL1em85DRgyrvAACsazjzfzg323.png "title=" 20160526234314348.png "alt=" Wkiol1em85drgyrvaacsazjzfzg323.png "/>
Note: The code adds the location as shown in
(3) Add a method to download the file in Uploadcontroller.java with the following code:
@RequestMapping (value = "/download", method = { requestmethod.get, requestmethod.post }) Public responseentity<byte[]> download (@RequestParam (name = "FileName") string filename,httpservletrequest request) {httpheaders headers = new httpheaders (); Pattern pattern = pattern.compile ("\\w*\\.\\w+"); Matcher matcher = pattern.matcher (filename);//check for illegal characters in file names, only letters, numbers, and underscores are allowed if (matcher.matches ( )) {try {headers.setcontentdispositionformdata ("MyFile", filename); Headers.setcontenttype ( Mediatype.application_octet_stream);// Gets the physical path String filepath = request.getsession (). Getservletcontext (). Getrealpath ("/uploads"); File pic = new file (Filepath, filename); return new responseentity<byte[] > (Fileutils.readfiletobytearray (pic), headers, httpstatus.created);} catch (Exception e) {e.printstacktrace ();}} Return null;}
Note: As can be seen from the code above, by receiving a string representing the file name and then stitching it up with the path of the file, the file object is formed on the real path to the disk, and finally the stream of the file is returned and downloaded. It is important to note that in order to prevent any file download from being downloaded to a file in another path, the format of the file name is verified before downloading. at the same time, a responseentity<byte[]> type of data is returned in order to return our custom httpheaders and httpstatus while returning the data stream.
(4) The results of the final download are as follows:
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/85/84/wKiom1em873C4HbmAAFpQB9gwPM589.jpg "title=" 20160526235931502.jpg "alt=" Wkiom1em873c4hbmaafpqb9gwpm589.jpg "/>
This article is from "Zifangsky's personal blog" blog, make sure to keep this source http://983836259.blog.51cto.com/7311475/1835373
Example of file download based on SPRINGMVC