SPRINGMVC: Study Notes (9)--File download

Source: Internet
Author: User

springmvc-File Download Description two cases

1. Provide the download service for the logged-in user.

2. Block access to the download only by entering the URL.

File Download Overview

In order to send the file to the browser, we need to do the following in the controller:

    1. Use the void return type for the request-handling method, and add the HttpServletResponse parameter to the method.
    2. Sets the content type of the response to the content type of the file. The Content-type header defines the type of data in the body of an entity and contains the media type and subtype identifiers. If the content type is not clear and you want the browser to always display the Save dialog box, set it to Application/octet-stream. This value is case-insensitive.
    3. Add an HTTP response header named Content-disposition, and assign a value of Attachment;filename=filename, where filename is the default file name.
Case 1: Providing download services for logged-in Users domain class
 Packagedomain; Public classLogin {PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}
Controller controllers
 PackageController;Importdomain. Login;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.web.bind.annotation.ModelAttribute;Importorg.springframework.web.bind.annotation.RequestMapping;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportJava.io.*; @Controller Public classResourcecontroller {Private Static FinalLog logger = Logfactory.getlog (Resourcecontroller.class); @RequestMapping (Value= "/login")     PublicString Login (@ModelAttribute login login, HttpSession session, model model) {Model.addattribute ("Login",NewLogin ()); if("MS". Equals (Login.getusername ()) && "123". Equals (Login.getpassword ())) {Session.setattribute ("LoggedIn", boolean.true); return"Main"; }        Else        {            return"LoginForm"; }} @RequestMapping (Value= "/resource_download")     PublicString Downloadresource (HttpSession session, HttpServletRequest request, httpservletresponse response) {
    if(session==NULL|| Session.getattribute ("loggedIn") = =NULL)        {        return"LoginForm"; } String dataDirectory= Request.getservletcontext (). Getrealpath ("/web-inf/data"); File File=NewFile (DataDirectory, "Blog.zip"); if(File.exists ()) {Response.setcontenttype ("Application/octet-stream"); Response.AddHeader ("Content-disposition", "Attachment;filename=blog.zip"); byte[] buffer =New byte[1024]; FileInputStream FIS=NULL; Bufferedinputstream bis=NULL; Try{FIS=Newfileinputstream (file); Bis=NewBufferedinputstream (FIS); OutputStream OS=Response.getoutputstream (); inti =bis.read (buffer);  while(I!=-1) {os.write (buffer,0, i); I=bis.read (buffer); }            } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally {                Try{bis.close (); } Catch(IOException e) {e.printstacktrace (); }                Try{fis.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        return NULL; }}
Writing views

main.jsp

<%@ Page ContentType="Text/html;charset=utf-8"language="Java" %><HTML><Head>    <title>Downpage</title></Head><Body>    <h4>Click the link to download the file</h4>    <P>        <ahref= "Resource_download" >Down</a>    </P></Body></HTML>

loginform.jsp

<%@ Page ContentType="Text/html;charset=utf-8"language="Java" %><HTML><Head>    <title>Login Page</title></Head><Body>    <Form:formCommandName= "Login"Action= "Login"Method= "POST">Account Number:<BR>        <Form:inputPath= "username"Csserrorclass= "Error"ID= "username"/>        <BR>Password:<BR>        <Form:inputPath= "Password"Csserrorclass= "Error"ID= "Password"/>        <BR> <inputtype= "Submit"value= "Submit">    </Form:form></Body></HTML>
Case 2: block access to downloads by simply entering a URL
@RequestMapping (value = "/resource_download")     PublicString Downloadresource (HttpSession session, HttpServletRequest request, httpservletresponse response,@ Requestheader String Refuer ) { if(refer==null  )//By judging the refer to the browser input URL can download the picture of the situation {return"LoginForm"; } String dataDirectory= Request.getservletcontext (). Getrealpath ("/web-inf/data"); File File=NewFile (DataDirectory, "Blog.zip"); if(File.exists ()) {Response.setcontenttype ("Application/octet-stream"); Response.AddHeader ("Content-disposition", "Attachment;filename=blog.zip"); byte[] buffer =New byte[1024]; FileInputStream FIS=NULL; Bufferedinputstream bis=NULL; Try{FIS=Newfileinputstream (file); Bis=NewBufferedinputstream (FIS); OutputStream OS=Response.getoutputstream (); inti =bis.read (buffer);  while(I!=-1) {os.write (buffer,0, i); I=bis.read (buffer); }            } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally {                Try{bis.close (); } Catch(IOException e) {e.printstacktrace (); }                Try{fis.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        return NULL; }}    

  

SPRINGMVC: Study Notes (9)--File download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.