Spring Boot入门(11)实现文件下载功能

news/2024/7/19 10:50:20 标签: python, 爬虫, java

  在这篇博客中,我们将展示如何在Spring Boot中实现文件的下载功能。
  还是遵循笔者写博客的一贯风格,简单又不失详细,实用又能让你学会。
  本次建立的Spring Boot项目的主要功能为文件下载,而且这也是唯一功能,当然,作为例子,要尽可能简单,所以,功能简化为只下载E盘music_eg目录下的某一个文件。
  该Spring Boot项目的名称为file_download,其具体结构如下:

项目结构

build.gradle文件的代码如下:

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.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下:

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;

@Controller
public class File_Download {

    //实现Spring Boot 的文件下载功能,映射网址为/download
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) throws UnsupportedEncodingException {

        // 获取指定目录下的第一个文件
        File scFileDir = new File("E://music_eg");
        File TrxFiles[] = scFileDir.listFiles();
        System.out.println(TrxFiles[0]);
        String fileName = TrxFiles[0].getName(); //下载的文件名

        // 如果文件名不为空,则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "E://music_eg/";
            File file = new File(realPath, fileName);

            // 如果文件名存在,则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                // 实现文件下载
                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 {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

}

这样我们就完成了Spring Boot的文件下载功能。什么?这样就搞定了?是的,就是这么简单,因为只实现了文件下载功能。具体的代码留给读者好好分析哦~~
  写完代码并不是我们的最终目的,我们还差最后一步,那就是测试!测试,真的相当重要啊~
  运行Spring Boot项目后,在浏览器中输入:http://localhost:8080/download , 你会发现什么?那就是你的浏览器已经开始下载E盘music_eg目录下的某一个文件啦(前提是E盘中存在music_eg目录,当然里面还得有文件,本例仅作为测试),如下图所示:

文件下载

  我们再去查看E盘music_eg目录,如下:

E盘music_eg目录

  So, 用Spring Boot实现文件下载功能搞定!欢迎大家交流哦~

注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~


http://www.niftyadmin.cn/n/1746065.html

相关文章

java字符集更改_Java过程修改dump文件成特定字符集

前一段时间在http://www.itpub.net/showthread.php...15&pagenumber1中讨论的DMP不同字符集之间自由转换工具,经过一位java朋友的帮忙,今天奉献上biti提议的java存储过程修改方法:DumpChange.java脚本:import java.io.*;public class Dum…

java 重定向输入_java 输入重定向

java 中从文件输入数据的方法 即使 输入输出流。模板如下package 第三章; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class Text2 { …

Tarjan 割点

//Tarjan 割点 //根节点满足子节点个数>2即为割点 //非根节点满足dfn[u]<low[v]时u即为割点 #include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> using namespace s…

java 7个数排序_Java数据结构(七)—— 排序算法

排序算法(Sort Algorithm)排序算法介绍和分类将一组数据&#xff0c;依指定顺序进行排列排序的分类内部排序指将需要处理的所有数据都加载到内部存储器中进行排序外部排序数据量过大&#xff0c;无法全部加载到内存中&#xff0c;需借助外部存储进行排序常见的排序算法冒泡排序…

AWS Config新增跨账户、跨区域数据聚合功能

近日&#xff0c;Amazon Web Services&#xff08;AWS&#xff09;增加了跨多个账户和/或区域聚合由AWS Config Rules生成的合规数据的功能&#xff0c;实现了AWS资源的集中审计和治理。新增的聚合仪表板视图展示了组织中不合规的规则。然后&#xff0c;用户可以下钻&#xff0…

java中使用不变类_为什么要用Java声明一个不变的类final?

慕姐8265434如果您不标记该类final&#xff0c;那么我可能会突然使您看似不变的类真正变得可变。例如&#xff0c;考虑以下代码&#xff1a;public class Immutable { private final int value; public Immutable(int value) { this.value value; } p…

JEPLUS之列表字段配置的几种查询方式——JEPLUS软件快速开发平台

为什么80%的码农都做不了架构师&#xff1f;>>> JEPLUS之列表字段配置的几种查询方式 我们在配置列表是往往在业务中都需要给字段加上一些查询项&#xff0c;这篇笔记我来给大家介绍下在JEPLUS中的几种列表字段查询配置。 一、效果展示 二、实现步骤 1、列表字段的…