Spring Boot Starter (10) for file download function

Source: Internet
Author: User

?? In this blog, we will show you how to implement the download function of a file in spring boot.
?? or follow the author to write a blog's consistent style, simple and yet detailed, practical and can let you learn.
?? The main function of this spring boot project is file download, and this is the only feature, of course, as an example, to be as simple as possible, so the function is simplified to download only one file under the E-disk Music_eg directory.
?? The name of the Spring boot project is file_download, with the following specific structure:

The code for the Build.gradle file is as follows:

buildscript {    ext {        springBootVersion = ‘2.0.3.RELEASE‘    }    repositories {        mavenCentral()    }    dependencies {        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")    }}apply plugin: ‘java‘apply plugin: ‘eclipse‘apply plugin: ‘org.springframework.boot‘apply plugin: ‘io.spring.dependency-management‘group = ‘com.example‘version = ‘0.0.1-SNAPSHOT‘sourceCompatibility = 1.8repositories {    mavenCentral()}dependencies {    compile(‘org.springframework.boot:spring-boot-starter-web‘)    testCompile(‘org.springframework.boot:spring-boot-starter-test‘)}

All we need to do is create a controller (controler) file, the File_download.java under the Controller directory, whose full directory is as follows:

Package Com.example.file_download. Controller;import Java.io.*;import Java.net.urlencoder;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.RequestMapping; @Controllerpublic class File_download {//Implement spring Boot                               File download function, the map URL is/download @RequestMapping ("/download") public String DownloadFile (HttpServletRequest request, HttpServletResponse response) throws Unsupportedencodingexception {//Get the first file under the specified directory Fi        Le scfiledir = new File ("E://music_eg");        File trxfiles[] = Scfiledir.listfiles ();        System.out.println (Trxfiles[0]); String fileName = Trxfiles[0].getname (); Download filename//If file name is not empty, download if (filename! = null) {//Set file path String Realpath = "E://mus            ic_eg/";            File File = new file (Realpath, fileName); If the file name exists, download the if (fiLe.exists ()) {//config file download response.setheader ("Content-type", "Application/octet-stream");                Response.setcontenttype ("Application/octet-stream"); The download file will display the Chinese Response.setheader ("content-disposition", "attachment;filename=" + urlencoder.encode (Filenam                E, "UTF-8"));                Implement file download byte[] buffer = new byte[1024];                FileInputStream FIS = null;                Bufferedinputstream bis = null;                    try {fis = new FileInputStream (file);                    bis = new Bufferedinputstream (FIS);                    OutputStream OS = Response.getoutputstream ();                    int i = bis.read (buffer);                        while (i! =-1) {os.write (buffer, 0, I);                    i = bis.read (buffer);                } System.out.println ("Download the song successfully!"); } catch(Exception e)                {System.out.println ("Download the song failed!"); } finally {if (bis! = null) {try {b                        Is.close ();                        } catch (IOException e) {e.printstacktrace (); }} if (FIS! = null) {try {FIS.C                        Lose ();                        } catch (IOException e) {e.printstacktrace ();    }}}}} return null; }}

This allows us to complete the spring boot file download function. What the? So it's done? Yes, it is that simple, because only the file download function is implemented. The specific code is left to the reader to analyze well.
?? After writing the code is not our ultimate goal, we are not the last step, that is the test! Test, really very important AH ~
?? After running the Spring boot project, enter in the browser: http://localhost:8080/download, what will you find? That is your browser has started to download the e-disk Music_eg directory of a file (provided that the E-disk exists in the Music_eg directory, of course, there must be files, this example only as a test), as shown:

?? Let's look at the e-disk Music_eg directory as follows:

?? So, with spring boot implementation of file download function! Welcome everyone to Exchange Oh ~

Note: I have now opened two public number: because Python (number: Python_math) and easy to learn the Python crawler (number: Easy_web_scrape), welcome to the attention OH ~ ~

Spring Boot Starter (10) for file download function

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.