项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。

新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.dalaoyang</groupId>
<artifactId>springboot_upload_download</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot_upload_download</name>
<description>springboot_upload_download</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.15</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

前台页面index.html,其中包含单个上传,下载,批量上传。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>单文件上传</p>
<form action="upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>文件下载</p>
<a href="download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="batch">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>

IndexController只是用来页面的跳转

package com.dalaoyang.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@Controller
public class IndexController { @RequestMapping("/")
public String index()
{
return "index";
}
}

最后是本文的重点,FileController,其中包含单个上传,单个下载,批量上传对应的方法。需要注意下载功能写的是对应我电脑里面固定位置的文件,仅供大家来参考。以下是代码:

package com.dalaoyang.Controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@RestController
public class FileController {
private static final Logger log = LoggerFactory.getLogger(FileController.class); @RequestMapping(value = "/upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
log.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("文件的后缀名为:" + suffixName);
// 设置文件存储路径
String filePath = "/Users/dalaoyang/Downloads/";
String path = filePath + fileName;
File dest = new File(path);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹
}
file.transferTo(dest);// 文件写入
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
} @PostMapping("/batch")
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
String filePath = "/Users/dalaoyang/Downloads/";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(filePath + file.getOriginalFilename())));//设置文件路径及名字
stream.write(bytes);// 写入
stream.close();
} catch (Exception e) {
stream = null;
return "第 " + i + " 个文件上传失败 ==> "
+ e.getMessage();
}
} else {
return "第 " + i
+ " 个文件上传失败因为文件为空";
}
}
return "上传成功";
} @GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "dalaoyang.jpeg";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File("/Users/dalaoyang/Documents/dalaoyang.jpeg");
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
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);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
}

SpringBoot文件上传下载的更多相关文章

  1. springboot文件上传下载简单使用

    springboot的文件上传比较简单 一.使用默认的Resolver:StandardServletMultipartResolver controller package com.mydemo.w ...

  2. springboot文件上传下载,转载的

    Spring Boot入门——文件上传与下载 原文来自:https://www.cnblogs.com/studyDetail/articles/7003253.html 1.在pom.xml文件中添 ...

  3. springboot 文件上传下载

    关键点: 1,使用 POST 请求2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE3,@RequestParm 里面的字符串和前端 input 控件的 na ...

  4. SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)

    SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...

  5. 补习系列(11)-springboot 文件上传原理

    目录 一.文件上传原理 二.springboot 文件机制 临时文件 定制配置 三.示例代码 A. 单文件上传 B. 多文件上传 C. 文件上传异常 D. Bean 配置 四.文件下载 小结 一.文件 ...

  6. Spring Boot2(十四):单文件上传/下载,文件批量上传

    文件上传和下载在项目中经常用到,这里主要学习SpringBoot完成单个文件上传/下载,批量文件上传的场景应用.结合mysql数据库.jpa数据层操作.thymeleaf页面模板. 一.准备 添加ma ...

  7. SpringMVC文件上传下载(单文件、多文件)

    前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...

  8. 一、手把手教你docker搭建fastDFS文件上传下载服务器

    在搭建fastDFS文件上传下载服务器之前,你需要准备的有一个可连接的linux服务器,并且该linux服务器上已经安装了docker,若还有没安装docker的,先百度自行安装docker. 1.执 ...

  9. Struts的文件上传下载

    Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...

随机推荐

  1. ActiveMQ消息的持久化策略

    持久化消息和非持久化消息的存储原理: 正常情况下,非持久化消息是存储在内存中的,持久化消息是存储在文件中的.能够存储的最大消息数据在${ActiveMQ_HOME}/conf/activemq.xml ...

  2. 【sqli-labs】Less18~Less22

    Less18: User-Agent注入,有错误回显 感叹一句,越来越难了.现在只能先看代码再分析怎么注入了..... 通过代码,发现username和password均做了校验.但是会有一个插入us ...

  3. hdu3635

    /* 一开始第a个球在第a个城市 操作T a b,把第a个球所在城市的所有球移到b所在的城市 操作Q a 要求输出 第a个球在哪个城市 第a个球所在的城市有几个球 第a个球移动次数 */ #inclu ...

  4. Repair the Wall

    问题 : Repair the Wall 时间限制: 1 Sec  内存限制: 128 MB 题目描述 Long time ago , Kitty lived in a small village. ...

  5. oracle数据库无法连接 The Network Adapter could not establish

    Caused by: java.sql.SQLException: Io 异常: The Network Adapter could not establish the connection 这个错误 ...

  6. 步步为营-86-WSFUpload组件

    文件上传组件,所需js文件和图片在百度网盘对应的文件夹下 <%@ Page Language="C#" AutoEventWireup="true" Co ...

  7. sqoop无法导出parquet文件到mysql

    1.问题描述 在CDH集群中我们需要将Hive表的数据导入到RDBMS数据库中,使用Sqoop工具可以方便的将Hive表数据抽取到RDBMS数据库中,在使用Sqoop抽取Hive Parquet表时作 ...

  8. 006-Python函数

    Python函数(def) 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段.Python提供了许多内建函数,比如print().但你也可以自己创建函数,这被叫做用户自定义函数.函数能 ...

  9. 使用 cacti 监控 windows 服务器硬盘的 I/O 状况

    https://blog.csdn.net/m0_37814112/article/details/80742433

  10. 学习笔记: 特性Attribute详解,应用封装

    /// /// 特性:中括号声明 /// /// 错觉:每一个特性都可以带来对应的功能 /// /// 实际上特性添加后,编译会在元素内部产生IL,但是我们是没办法直接使用的, /// 而且在meta ...