SpringBoot 文件上传和下载的实现源码
作者:dmfrm 发布时间:2021-05-28 14:12:46
标签:spring,boot,文件上传,下载
本篇文章介绍SpringBoot的上传和下载功能。
一、创建SpringBoot工程,添加依赖
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
工程目录为:
Application.java 启动类
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
二、创建测试页面
在resources/templates目录下新建uploadForm.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
<div>
<ul>
<li th:each="file : ${files}">
<a th:href="${file}" rel="external nofollow" th:text="${file}" />
</li>
</ul>
</div>
</body>
</html>
三、新建StorageService服务
StorageService接口
package hello.storage;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
StorageService实现
package hello.storage;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.function.Predicate;
import java.util.stream.Stream;
@Service
public class FileSystemStorageService implements StorageService
{
private final Path rootLocation = Paths.get("upload-dir");
/**
* 保存文件
*
* @param file 文件
*/
@Override
public void store(MultipartFile file)
{
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try
{
if (file.isEmpty())
{
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains(".."))
{
// This is a security check
throw new StorageException("Cannot store file with relative path outside current directory " + filename);
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
throw new StorageException("Failed to store file " + filename, e);
}
}
/**
* 列出upload-dir下面所有文件
* @return
*/
@Override
public Stream<Path> loadAll()
{
try
{
return Files.walk(this.rootLocation, 1) //path -> !path.equals(this.rootLocation)
.filter(new Predicate<Path>()
{
@Override
public boolean test(Path path)
{
return !path.equals(rootLocation);
}
});
}
catch (IOException e)
{
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename)
{
return rootLocation.resolve(filename);
}
/**
* 获取文件资源
* @param filename 文件名
* @return Resource
*/
@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);
}
}
/**
* 删除upload-dir目录所有文件
*/
@Override
public void deleteAll()
{
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
/**
* 初始化
*/
@Override
public void init()
{
try
{
Files.createDirectories(rootLocation);
}
catch (IOException e)
{
throw new StorageException("Could not initialize storage", e);
}
}
}
StorageException.java
package hello.storage;
public class StorageException extends RuntimeException {
public StorageException(String message) {
super(message);
}
public StorageException(String message, Throwable cause) {
super(message, cause);
}
}
StorageFileNotFoundException.java
package hello.storage;
public class StorageFileNotFoundException extends StorageException {
public StorageFileNotFoundException(String message) {
super(message);
}
public StorageFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
四、Controller创建
将上传的文件,放到工程的upload-dir目录,默认在界面上列出可以下载的文件。
listUploadedFiles函数,会列出当前目录下的所有文件
serveFile下载文件
handleFileUpload上传文件
package hello;
import java.io.IOException;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import hello.storage.StorageFileNotFoundException;
import hello.storage.StorageService;
@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();
}
}
源码下载:https://github.com/HelloKittyNII/SpringBoot/tree/master/SpringBootUploadAndDownload
总结
以上所述是小编给大家介绍的SpringBoot 文件上传和下载的实现源码网站的支持!
来源:https://blog.csdn.net/u010889616/article/details/79764175


猜你喜欢
- 从什么是IOC开始?Spring——春天,Java编程世界的春天是由一位音乐家—
- 1 概述Java虚拟机把描述类的数据从Class文件加载到内存, 并对数据进行校验、转化解析和初始化,最终形成可以被虚拟机直接使用的Java
- 概述Handler是Android消息机制的上层接口。通过它可以轻松地将一个任务切换到Handler所在的线程中去执行。通常情况下,Hand
- 本文实例讲述了Java实现的RSA加密解密算法。分享给大家供大家参考,具体如下:import java.awt.AlphaComposite
- 先看一段代码: private DataSet GetDataSet(string strsql){ string s
- 为公司系统业务需要,这几天了解了一下微信和支付宝扫码支付的接口,并用c#实现了微信和支付宝扫码支付的功能。微信支付分为6种支付模式:1.付款
- C语言代码由上到下依次执行,原则上函数定义要出现在函数调用之前,否则就会报错。但在实际开发中,经常会在函数定义之前使用它们,这个时候就需要提
- 前言字符串分割函数strtok,大家可能都知道他怎么使用,一旦要用的时候就会心生疑惑,不知道它的内部的实现,废话不多说,本篇就来带大家看看s
- Spring Boot项目默认的会打包成单一的jar文件,但是有时候我们并不想让配置文件、依赖包都跟可执行文件打包到一起。这时候可以在pom
- 在开发过程中,我们可能会经常遇到这样的需求样式:这张图是截取京东消息通知的弹出框,我们可以看到右上方有个三角形的气泡效果,这只是其中一种,三
- Gateway 修改HTTP响应信息实践Spring Cloud的过程中,使用Gateway作为路由组件,并且基于Gateway实现权限的验
- 一.并行LINQSystem.Linq名称空间中包含的类ParallelEnumerable可以分解查询的工作,使其分布在多个线程上。尽管E
- Lambda表达式的心得如题,因为博主也是最近才接触到Lambda表达式的(PS 在这里汗颜一会)。我并不会讲解它的原理,诚然任何一件事物如
- 1.线索化二叉树的介绍将数列 {1, 3, 6, 8, 10, 14 } 构建成一颗二叉树.问题分析:1.当我们对上面的二叉树进行中序遍历时
- 最近几个项目的测试结果,Android无法主动通过调用 webview.loadUrl("javascript:"+ca
- 实现了Java web开发账号单一登录的功能,防止同一账号重复登录,后面登录的踢掉前面登录的,使用过滤器Filter实现的。可以先下载项目下
- 现在智能手机基本都是触摸操作,点击按钮是一种交互方式,同时手势相关的操作,比如滑动等等同样是很重要的交互方式。这篇文章是对安卓手势交互相关知
- Struts2 Action/动作动作是Struts2框架的核心,因为他们的任何MVC(模型 - 视图 - 控制器)框架。每个URL将被映射
- springboot aop里的@Pointcut()的配置@Pointcut("execution(public * com.w
- 本文实例为大家分享了Android实现欢迎滑动页面的具体代码,供大家参考,具体内容如下一、效果图二、源码1.activity_welcome