SpringBoot上传任意文件功能的实现
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
@Controller
public class FileUploadController {
private final StorageService storageService; @Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
} //展示上传过的文件
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException { model.addAttribute("files", storageService.loadAll().map(path ->
MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList())); return "uploadForm";
} //下载选定的上传的文件
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename) { Resource file = storageService.loadAsResource(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
.body(file);
} //上传文件
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) { storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!"); return "redirect:/";
} @ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
@Service
public class FileSystemStorageService implements StorageService { private final Path rootLocation; @Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
} @Override
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
} @Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, )
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
} } @Override
public Path load(String filename) {
return rootLocation.resolve(filename);
} @Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if(resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException("Could not read file: " + filename); }
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
} @Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
} @Override
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB
![](https://images2017.cnblogs.com/blog/1190618/201708/1190618-20170801183357646-1632767289.png)
![](https://images2017.cnblogs.com/blog/1190618/201708/1190618-20170801183446396-1904400924.png)
SpringBoot上传任意文件功能的实现的更多相关文章
- Springboot 上传CSV文件并将数据存入数据库
.xml文件依赖配置 <!--csv依赖 --> <dependency> <groupId>org.apache.commons</groupId> ...
- springboot上传下载文件
在yml配置相关内容 spring: # mvc: throw-exception-if-no-handler-found: true #静态资源 static-path-pattern: /** r ...
- 解决springBoot上传大文件异常问题
上传文件过大时的报错: org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size ex ...
- springboot上传linux文件无法浏览,提示404错误
1.配置文件地址置换 @Componentclass WebConfigurer implements WebMvcConfigurer { @Autowired ConfigUtil bootdoC ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- WebSSH画龙点睛之lrzsz上传下载文件
本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...
- springboot整合ueditor实现图片上传和文件上传功能
springboot整合ueditor实现图片上传和文件上传功能 写在前面: 在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作: springboot+layui 整合百度富文本 ...
- WEB安全第二篇--用文件搞定服务器:任意文件上传、文件包含与任意目录文件遍历
零.前言 最近做专心web安全有一段时间了,但是目测后面的活会有些复杂,涉及到更多的中间件.底层安全.漏洞研究与安全建设等越来越复杂的东东,所以在这里想写一个系列关于web安全基础以及一些讨巧的pay ...
- PHP中使用Session配合Javascript实现文件上传进度条功能
Web应用中常需要提供文件上传的功能.典型的场景包括用户头像上传.相册图片上传等.当需要上传的文件比较大的时候,提供一个显示上传进度的进度条就很有必要了. 在PHP .4以前,实现这样的进度条并不容易 ...
随机推荐
- 关于HTML学习整理(一)
新人,自己整理,第一次发,以后慢慢整理,欢迎指点,那些链接怎么做的,希望有人告知一下,谢谢! HTML页面写法,标签成对出现,可嵌套使用 <html> <head> <t ...
- 【JavaScript学习】-JS内置对象1-对象概述
对象(object): JavaScript 中的所有事物都是对象,如:字符串.数值.数组.函数等,每个对象带有属性和 方法.JavaScript 提供多个内建对象,比如 String.Date.Ar ...
- MVC过滤器之添加LoginAttribute,浏览器bug:重定向次数太多
以前在写登录Action过滤时,都在每个Controller前写上CheckLoginAttribute:这次决定偷懒试一下能否将所有Action和Controller统一过滤: 出bug的代码是这样 ...
- JAVAEE学习笔记
以后创建常量有三个名字:Constant SystemParas StaticValue 上限或者下限命名 max_ min_ 包含的范围命名 first l ...
- 大数据 Hadoop,Spark和Storm
大数据(Big Data) 大数据,官方定义是指那些数据量特别大.数据类别特别复杂的数据集,这种数据集无法用传统的数据库进行存储,管理和处理.大数据的主要特点为数据量大(Volume),数据类别复 ...
- 鼠标滚轮图片放大缩小功能,使用layer弹框后不起作用
今天在项目中遇到的一个问题:点击按钮使用layer弹框弹出一张图片,需要加一个鼠标滚轮放大缩小,图片也跟着放大缩小的功能.于是在网上找了一个demo. DEMO: <!DOCTYPE html ...
- [leetcode-434-Number of Segments in a String]
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of ...
- 【Android Developers Training】 28. 将用户带领到另一个应用
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- WCF学习——构建第二个WCF应用程序(六)
一.创建客户端应用程序 若要创建客户端应用程序,你将另外添加一个项目,添加对该项目的服务引用,配置数据源,并创建一个用户界面以显示服务中的数据.若要创建客户端应用程序,你将另外添加一个项目,添加对该项 ...
- 浅谈 Requests包
浅谈 Requests包 一:Requests包是做什么的? 简单地说,是用python处理HTTP的一个包. 它的标志也非常有气质,是一个双蛇杖,按照官方的说法,一条蛇代表client,一条代表se ...