SpringBoot文件上传下载
项目中经常会有上传和下载的需求,这篇文章简述一下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文件上传下载的更多相关文章
- springboot文件上传下载简单使用
springboot的文件上传比较简单 一.使用默认的Resolver:StandardServletMultipartResolver controller package com.mydemo.w ...
- springboot文件上传下载,转载的
Spring Boot入门——文件上传与下载 原文来自:https://www.cnblogs.com/studyDetail/articles/7003253.html 1.在pom.xml文件中添 ...
- springboot 文件上传下载
关键点: 1,使用 POST 请求2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE3,@RequestParm 里面的字符串和前端 input 控件的 na ...
- SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)
SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...
- 补习系列(11)-springboot 文件上传原理
目录 一.文件上传原理 二.springboot 文件机制 临时文件 定制配置 三.示例代码 A. 单文件上传 B. 多文件上传 C. 文件上传异常 D. Bean 配置 四.文件下载 小结 一.文件 ...
- Spring Boot2(十四):单文件上传/下载,文件批量上传
文件上传和下载在项目中经常用到,这里主要学习SpringBoot完成单个文件上传/下载,批量文件上传的场景应用.结合mysql数据库.jpa数据层操作.thymeleaf页面模板. 一.准备 添加ma ...
- SpringMVC文件上传下载(单文件、多文件)
前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...
- 一、手把手教你docker搭建fastDFS文件上传下载服务器
在搭建fastDFS文件上传下载服务器之前,你需要准备的有一个可连接的linux服务器,并且该linux服务器上已经安装了docker,若还有没安装docker的,先百度自行安装docker. 1.执 ...
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
随机推荐
- 对<tr><td>标签里的input 循环取值
需求描述:单击table整行,跳转到具体的信息页面 关键就是获取整行的id,传给后台做查询,返回list 解决思路:用带参数函数传过去id,然后在js的函数中用$("#id"). ...
- Anaconda创建caffe和tensorflow共存环境
一.前言 安装环境: Anaconda Ubuntu 二.安装步骤 我们分几步进行,anconda的安装和使用方法就不讲解了.我们直接安装caffe和tensorflow. 1.创建虚拟环境 我们先创 ...
- laravel 不理解的call方法
返回结果: 原来是调用同控制器的这四个方法之一...vendor\zhiyicx\plus-question\src\API2\Controllers\UserQuestionController.p ...
- 高斯消元模板!!!bzoj1013
/* 高斯消元模板题 n维球体确定圆心必须要用到n+1个点 设圆心坐标(x1,x2,x3,x4...xn),半径为C 设第i个点坐标为(ai1,ai2,ai3,,,ain)那么对应的方程为 (x1-a ...
- INFO JobScheduler: Added jobs for time 1524468752000 ms/INFO MemoryStore: Block input-0-1524469143000 stored as bytes in memory/完全分布式 ./bin/run-example streaming.NetworkWordCount localhost 9999无法正常运行
1.完全分布式 ./bin/run-example streaming.NetworkWordCount localhost 9999无法正常运行: 1 [hadoop@slaver1 spark- ...
- 最大子数组(I, II, III,IV,V)和最大子数组乘积 (动态规划)
I 找一个连续最大子数组,sum加到nums[i], 如果前面子数组和<0则舍去,从头开始. class Solution { public: /** * @param nums: A list ...
- JSP基础知识➣结构及生命周期(一)
概述 网络服务器需要一个JSP引擎,也就是一个容器来处理JSP页面.容器负责截获对JSP页面的请求.本教程使用内嵌JSP容器的Apache来支持JSP开发. JSP容器与Web服务器协同合作,为JSP ...
- Python自带IDE设置字体
打开Python 3.7.0 shell 点击菜单项 “”Options“”>"Configure IDLE" 可选择窗口的字体和大小 可选择背景主题颜色 可自定义配置
- 【Android】 textview 中超出屏幕宽度的字符 省略号显示
当利用textview显示内容时,显示内容过多可能会折行或显示不全,那样效果很不好. 实现如下: <TextView android:layout_width="fill_parent ...
- Flink--sink到kafka
package com.flink.DataStream import java.util.Properties import org.apache.flink.api.common.serializ ...