项目中经常会有上传和下载的需求,这篇文章简述一下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. 进程与程序 并行 并发 串行 阻塞 join函数

    进程是正在运行的程序,程序是程序员编写的一对代码,也就是一堆字符,当这堆代码被系统加载到内存并执行,就有了进程. (需要注意的是:一个程序是可以产生多个程序,就像我们可以同时运行多个QQ程序一样,会形 ...

  2. 【scapy】读取pcap

    scapy读取pcap包 假设有pcap包test.pcap,读取其中的分层流量信息 代码: import scapy_http.http try: import scapy.all as scapy ...

  3. Unity3D用户手册

    Unity Manual 用户手册 Welcome to Unity. 欢迎使用Unity. Unity is made to empower users to create the best int ...

  4. tensorflow(2):神经网络优化(loss,learning_rate)

    案例: 预测酸奶的日销量, 由此可以准备产量, 使得损失小(利润大),假设销量是y , 影响销量的有两个因素x1, x2, 需要预先采集数据,每日的x1,x2和销量y_, 拟造数据集X,Y_, 假设y ...

  5. hdu4966 最小树形图+虚根

    /* 辛辛苦苦调试半天, 过了样例,竟然没有ac!! 网上对比了ac代码,感觉添加一个虚根就能ac 但是想不明白为什么 */ /* 第二天想了下,知道了为什么wa:因为从等级0连到其他课程等级i的不止 ...

  6. Microsoft Visual Studio Community 2017 修改新建项目的默认位置

    IDE: Microsoft Visual Studio Community 2017 15.5.2 通过修改默认的设置,在下一次新建项目时,就可以节省一些不必要的操作. 菜单:工具 > 选项, ...

  7. Centos系统压力测试 ab 命令安装与使用

    Apache安装包中自带的压力测试工具 Apache Benchmark(简称ab) 简单易用,这里就采用 ab作为压力测试工具了. 1.独立安装 ab运行需要依赖apr-util包,安装命令为: y ...

  8. .tar.xz文件的解压方法

    废话不多说: 直接看 方法一: tar -xvJf ***.tar.gz 方法二: 先减压成 .tar 格式的文件, 再解压 .tar #xz是一个工具, 系统中没有安装,需要下载 xz -d *** ...

  9. Python零基础入门之Tkinter的对话框

    这篇博客主要是总结一下Tkinter中的对话框的使用,值得一提的是自从python3.0之后关于关于对话框的模块(messagebox.filedialog.colorchooser)都被收归到了tk ...

  10. windows下KafkaOffsetMonitor下载及安装

    KafkaOffsetMonitor是一个可视化工具的jar包,如KafkaOffsetMonitor-assembly-0.2.1.jar,用来来监控kafka的使用状态. 一.下载地址 https ...