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
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以前,实现这样的进度条并不容易 ...
随机推荐
- nodejs构建多房间简易聊天室
1.前端界面代码 前端不是重点,够用就行,下面是前端界面,具体代码可到github下载. 2.服务器端搭建 本服务器需要提供两个功能:http服务和websocket服务,由于node的事件驱动机制, ...
- .NET Core程序中使用User Secrets存储敏感数据
前言 在开发中经常会用到一些敏感数据,比如AppSecret或数据库连接字符串,无论是硬编码还是写在配置文件中,最终都要push到svn或git上.对于开源项目,这些敏感数据就无隐私可言了,对于私有项 ...
- Java学习笔记--反射API
反射API 1.反射API的介绍 通过反射API可以获取Java程序在运行时刻的内部结构.比如Java类中包含的构造方法.域和方法等元素,并可以与这些元素进行交换. 按照 一般地面向对象的设计 ...
- template might not exist or might not be accessible by any of the configured Template Resolvers
距离上一篇文章已经很长时间了,最近太忙碌了,今天发布spring boot遇到一个问题,找了好久才找到解决办法,今天贴出来和大家一起分享下,首先看错误信息 HTTP Status 500 - Requ ...
- xUtils使用详细介绍
xUtils3使用详解 一.xUtils简介: xUtils是基于Afinal开发的目前功能比较完善的一个Android开源框架,官网:https://github.com/wyouflf/xUtil ...
- 霍尔开关MH253ESO在减压神器指尖手指陀螺中的作用
手指陀螺首先在欧美国家流行起来,现如今又在国外掀起一帆狂潮,它是一款排遣无聊的小玩具,又被称为减压神器. 其工作原理:是由一个双向的对称体作为主体,在主体中间嵌入一个轴承的设计组合,整体构成一个可平面 ...
- Bootstrap提示信息(标签、徽章、巨幕和页头)
前面的话 在Bootstrap中,有一些组件用于提示信息,如 标签.徽章.巨幕和页头.本文将详细介绍Bootstrap提示信息 标签 在一些Web页面中常常会添加一个标签用来告诉用户一些额外的信息,比 ...
- 2017寒假零基础学习Python系列之函数之 返回多个值
Python也和C语言一样有自己的标准库,不过在Python中叫做模块(module),这个和C语言中的头文件以及Java中的包类似,其中math就是其中之一,math模块中提供了sin()和cos( ...
- (转载)JAVA中八种基本数据类型的默认值
原文链接: http://simon-c.iteye.com/blog/1016031 引用 For type byte, the default value is zero, that is, th ...
- React环境配置
现在开始配置一个基础项目. 创建项目文件夹:C:\Users\Danny\Desktop\React npm init 创建package.json文件 下面的所有安装,都是--save-dev,因为 ...