SPRING4 MVC File Download instance

Source: Internet
Author: User

This article will show you how to perform a file download using spring MVC4, and we'll see the application download files from inside the file system as well as from external files.

Key highlights of this tutorial:

The download file is fairly straightforward and involves the following steps.

    • Create a InputStream to file for download.
    • Find the contents of the MIME type download file.
      – Can be application/pdf, text/html,application/xml,image/png and so on.
    • The content type responds to the MIME type found above (httpservletresponse).
      Response.setcontenttype (MimeType);
    • Set the content length for the MIME type found above.
      Response.setcontentlength (File.getlength ());//length in bytes
    • Sets the content-handling header for the response.
      Response.setheader ("Content-disposition", "attachment; Filename= "+ fileName); As the attachments file is downloaded. A "Save as" browser-based Settings dialog box may be displayed.

      Response.setheader ("content-disposition", "inline; Filename= "+ fileName"///via "inline" browser will try to display content into the browser (image, PDF, text, ...) )。 For other content types, the files are downloaded directly.

    • Copy the byte response from InputStream to OutputStream.
    • Once the replication is complete, turn off the input and output stream.

The complete embodiment is discussed below.

Use the following technologies:

    • Spring 4.2.0.RELEASE
    • Bootstrap v3.3.2
    • Maven 3
    • JDK 1.7
    • Tomcat 8.0.21
    • Eclipse JUNO Service Release 2

Now let's get started.

Project structure

declaring dependencies in Pom.xml
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.yiibai.springmvc</groupId> <artifactId> Spring4mvcfiledownloadexample</artifactid> <packaging>war</packaging> <version>1.0.0< /version> <name>spring4mvcfiledownloadexample Maven webapp</name> <properties>< Springframework.version>4.2.0.release</springframework.version></properties><dependencies ><dependency><groupid>org.springframework</groupid><artifactid>spring-webmvc</ Artifactid><version>${springframework.version}</version></dependency><dependency> <groupid>javax.servlet</groupid><artifactid>javax.servlet-api</artifactid><version >3.1.0</veRsion></dependency><dependency><groupid>javax.servlet</groupid><artifactid> Jstl</artifactid><version>1.2</version></dependency></dependencies><build> <pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId><version>2.4</version><configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory><warName> spring4mvcfiledownloadexample</warname><failonmissingwebxml>false</failonmissingwebxml></ Configuration></plugin></plugins></pluginmanagement><finalname>  Spring4mvcfiledownloadexample</finalname></build></project>
Create a Controller
Package Com.yiibai.springmvc.controller;import Java.io.bufferedinputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;import Java.net.urlconnection;import Java.nio.charset.charset;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.util.filecopyutils;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestMethod; @Controllerpublic class Filedownloadcontroller {private Static final string internal_file= "Irregular-verbs-list.pdf";p rivate static final string external_file_path= "c:/ Mytemp/springmvchibernatemanytomanycrudexample.zip "; @RequestMapping (value={"/","/welcome "}, Method = requestmethod.get) public String gethomepage (Modelmap model) {return "Welcome";} /* * Download a filE from *-Inside project, located in Resources folder.  *-Outside project, located in File system somewhere. */@RequestMapping (value= "/download/{type}", method = requestmethod.get) public void DownloadFile (HttpServletResponse Response, @PathVariable ("type") String type) throws IOException {File File = null;if (type.equalsignorecase ("internal")) {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); file = new file (Classloader.getresource ( Internal_file). GetFile ());} Else{file = new file (External_file_path);} if (!file.exists ()) {String errormessage = "Sorry. The file is looking for does not exist "; System.out.println (errormessage); OutputStream outputstream = Response.getoutputstream (); Outputstream.write ( Errormessage.getbytes (Charset.forname ("UTF-8")); Outputstream.close (); return;} String mimetype= Urlconnection.guesscontenttypefromname (File.getname ()), if (mimetype==null) {System.out.println (" MimeType is not detectable, would take default "); mimetype =" application/octEt-stream ";}        System.out.println ("mimetype:" +mimetype);                Response.setcontenttype (MimeType); /* "Content-disposition:inline" would show viewable types [like images/text/pdf/anything viewable by browser] right on BR Owser while others (zip e.g) would be directly downloaded [could provide Save as popup, based on your browser sett Ing.] */Response.setheader ("Content-disposition", String.Format ("inline;                Filename=\ "" + file.getname () + "\" ")); /* "Content-disposition:attachment" would be directly download, could provide Save as popup, based on your browser setting* ///response.setheader ("Content-disposition", String.Format ("attachment;                Filename=\ "%s\" ", File.getname ())); Response.setcontentlength (int) file.length ()) InputStream InputStream = new Bufferedinputstream (New FileInputStream        (file));        Copy bytes from source to destination (OutputStream in this example), closes both streams. Filecopyutils.copy (inputstReam, Response.getoutputstream ());}} 

The controller consists of two files. A file is an internal application (internal resource), and other files are located outside the file system of the application. Your project must change the path of the external file. For illustrative purposes only, we have an additional path variable (internal/external) in the path. We are using the Spring Filecopyutils tool class flow to copy from source to destination.

Configuration
Package Com.yiibai.springmvc.configuration;import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Org.springframework.web.servlet.config.annotation.enablewebmvc;import Org.springframework.web.servlet.config.annotation.resourcehandlerregistry;import Org.springframework.web.servlet.config.annotation.viewresolverregistry;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;import Org.springframework.web.servlet.view.internalresourceviewresolver;import Org.springframework.web.servlet.view.JstlView; @Configuration @enablewebmvc@componentscan (basepackages = " COM.YIIBAI.SPRINGMVC ") public class Helloworldconfiguration extends webmvcconfigureradapter{@Override public void Configureviewresolvers (Viewresolverregistry registry) {Internalresourceviewresolver Viewresolver = new InternalRes        Ourceviewresolver ();        Viewresolver.setviewclass (Jstlview.class); Viewresolver.setprefix ("/web-inf/views/");        Viewresolver.setsuffix (". jsp");    Registry.viewresolver (Viewresolver); } @Override public void Addresourcehandlers (Resourcehandlerregistry registry) {Registry.addresourcehandl    ER ("/static/**"). Addresourcelocations ("/static/"); }}
Initialization
Package Com.yiibai.springmvc.configuration;import Org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public class Helloworldinitializer extends Abstractannotationconfigdispatcherservletinitializer {     @Override    protected Class<?>[] Getrootconfigclasses () {        return new class[] {helloworldconfiguration.class};    }      @Override    protected class<?>[] getservletconfigclasses () {        return null;    }      @Override    protected string[] Getservletmappings () {        return new string[] {"/"};    }  }
Add a View
 <%@ taglib prefix= "form" uri= "Http://www.springframework.org/tags/form"%><%@ taglib prefix= "C" uri= " Http://java.sun.com/jsp/jstl/core "%>
Build, deploy, and run applications

Now build the war (in the previous Eclipse tutorial) or via MAVEN's command line (mvn clean install). Deploy the war to the Servlet3.0 container. Or:

Open Browser, browse http://localhost:8080/Spring4MVCFileDownloadExample

Click a second link. External files should be downloaded.

Click on the first link. The internal file [this is a PDF] should be displayed in the browser, which is due to content-disposition:inline. By inline, if the content can be displayed through the browser, it will show it in the browser.

Now change the content disposition notes from inline. Build and deploy. Click on the first link. This time you should see the PDF file being downloaded.

That's it, finish.

SPRING4 MVC File Download instance

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.