基于Spring实现文件上传功能

本小节你将建立一个可以接受HTTP multi-part 文件的服务。

你将建立一个后台服务来接收文件以及前台页面来上传文件。

要利用servlet容器上传文件,你要注册一个MultipartConfigElement类,以往需要在web.xml 中配置<multipart-config>,
而在这里,你要感谢SpringBoot,一切都为你自动配置好了。

1、新建一个文件上传的Controller:

应用已经包含一些 存储文件 和 从磁盘中加载文件 的类,他们在cn.tiny77.guide05这个包下。我们将会在FileUploadController中用到这些类。

package cn.tiny77.guide05;

import java.io.IOException;
import java.util.List;
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;

@Controller
public class FileUploadController {

 private final StorageService storageService;

 @Autowired
 public FileUploadController(StorageService storageService) {
  this.storageService = storageService;
 }

 @GetMapping("/")
 public String listUploadedFiles(Model model) throws IOException {

  List<String> paths = storageService.loadAll().map(
    path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
      "serveFile", path.getFileName().toString()).build().toString())
    .collect(Collectors.toList());

  model.addAttribute("files", paths);

  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();
 }

}

该类用@Controller注解,因此SpringMvc可以基于它设定相应的路由。每一个@GetMapping和@PostMapping注解将绑定对应的请求参数和请求类型到特定的方法。

GET / 通过StorageService 扫描文件列表并 将他们加载到 Thymeleaf 模板中。它通过MvcUriComponentsBuilder来生成资源文件的连接地址。

GET /files/{filename} 当文件存在时候,将加载文件,并发送文件到浏览器端。通过设置返回头"Content-Disposition"来实现文件的下载。

POST / 接受multi-part文件并将它交给StorageService保存起来。

你需要提供一个服务接口StorageService来帮助Controller操作存储层。接口大致如下

package cn.tiny77.guide05;

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();

}

以下是接口实现类

package cn.tiny77.guide05;

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.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
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;

@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) {
  String filename = StringUtils.cleanPath(file.getOriginalFilename());
  try {
   if (file.isEmpty()) {
    throw new StorageException("无法保存空文件 " + filename);
   }
   if (filename.contains("..")) {
    // This is a security check
    throw new StorageException(
      "无权访问该位置 "
        + filename);
   }
   Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
     StandardCopyOption.REPLACE_EXISTING);
  }
  catch (IOException e) {
   throw new StorageException("无法保存文件 " + filename, e);
  }
 }

 @Override
 public Stream<Path> loadAll() {
  try {
   return Files.walk(this.rootLocation, 1)
     .filter(path -> !path.equals(this.rootLocation))
     .map(path -> this.rootLocation.relativize(path));
  }
  catch (IOException e) {
   throw new StorageException("读取文件异常", 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(
      "无法读取文件: " + filename);

   }
  }
  catch (MalformedURLException e) {
   throw new StorageFileNotFoundException("无法读取文件: " + filename, e);
  }
 }

 @Override
 public void deleteAll() {
  FileSystemUtils.deleteRecursively(rootLocation.toFile());
 }

 @Override
 public void init() {
  try {
   Files.createDirectories(rootLocation);
  }
  catch (IOException e) {
   throw new StorageException("初始化存储空间出错", e);
  }
 }
}

2、建立一个Html页面

这里使用Thymeleaf模板

<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>

页面主要分为三部分分

- 顶部展示SpringMvc传过来的信息
- 一个提供用户上传文件的表单
- 一个后台提供的文件列表

3、限制上传文件的大小

在文件上传的应用中通常要设置文件大小的,想象一下后台处理的文件如果是5GB,那得多糟糕!在SpringBoot中,我们可以通过属性文件来控制。
新建一个application.properties,代码如下:
spring.http.multipart.max-file-size=128KB #文件总大小不能超过128kb
spring.http.multipart.max-request-size=128KB #请求数据的大小不能超过128kb

4、应用启动函数

package cn.tiny77.guide05;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

 @Bean
 CommandLineRunner init(StorageService storageService) {
  return (args) -> {
   storageService.deleteAll();
   storageService.init();
  };
 }
}

5、运行结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringMVC文件上传的配置实例详解

    记述一下步骤以备查. 准备工作: 需要把Jakarta Commons FileUpload及Jakarta Commons io的包放lib里. 我这边的包是: commons-fileupload-1.1.1.jar commons-io-1.3.2.jar 然后在spring-servlet.xml进行multipartResolver配置,不配置好上传会不好用. <bean id="multipartResolver" class="org.springfram

  • SpringMVC文件上传 多文件上传实例

    必须明确告诉DispatcherServlet如何处理MultipartRequest.SpringMVC中提供了文件上传使用方式如下配置xxx-servlet.xml,添加如下代码: 复制代码 代码如下: <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <!-- 设置

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

  • SpringMVC 文件上传配置,多文件上传,使用的MultipartFile的实例

    基本的SpringMVC的搭建在我的上一篇文章里已经写过了,这篇文章主要说明一下如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤 文件上传项目的源码下载地址:demo 一.配置文件: SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file <!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->

  • springMVC配置环境实现文件上传和下载

    最近的项目中用到了文件的上传和下载功能,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试. 下面就是springMVC配置环境实现文件上传和下载的具体步骤,供大家参考,具体内容如下 一. 基础配置: maven导包及配置pom.xml,导包时除开springmvc的基础依赖外,需要导入文件上传下载时用到的commons-io.jsr和commons-fileupload.jar: <project xmlns="http://maven.apache.org/POM/4.0.0&

  • MyBatis与SpringMVC相结合实现文件上传、下载功能

    环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中:如何从数据库下载文件,和显示图像文件并实现缩放. 将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob. 首先要创建数据库,此处使用MySql数据库. 注意:文中给出的代码多为节选重要片段,并不齐全. 1. 前期准备 使用maven创建一个springMVC+spring+mybatis+mysql的项目

  • Spring Boot实现文件上传示例代码

    使用SpringBoot进行文件上传的方法和SpringMVC差不多,本文单独新建一个最简单的DEMO来说明一下. 主要步骤包括: 1.创建一个springboot项目工程,本例名称(demo-uploadfile). 2.配置 pom.xml 依赖. 3.创建和编写文件上传的 Controller(包含单文件上传和多文件上传). 4.创建和编写文件上传的 HTML 测试页面. 5.文件上传相关限制的配置(可选). 6.运行测试. 项目工程截图如下: 文件代码: <dependencies>

  • jquery.form.js框架实现文件上传功能案例解析(springmvc)

    上一篇 Bootstrap自定义文件上传下载样式(http://www.jb51.net/article/85156.htm)已经有一段时间了,一直在考虑怎么样给大家提交一篇完美的逻辑处理功能.现在我结合自己的实际工作给大家分享一下. 使用的技术有jquery.form.js框架, 以及springmvc框架.主要实现异步文件上传的同时封装对象,以及一些注意事项. 功能本身是很简单的,但是涉及到一些传递参数类型的问题.例如:jquery的ajax方法与jquery.form.js中的ajaxSu

  • Spring实现文件上传(示例代码)

    在实际开发中,经常遇到要实现文件上传到服务器端的功能.Spring可以继承commons-fileupload插件来实现文件上传的功能.分为前端JSP编写和后台Controller的编写. 前期准备工作,首先要引入commons-fileupload这个jar包,pom.xml中的配置如下: 复制代码 代码如下: <!-- 实现文件上传,spring集成了这个功能 --><dependency> <groupId>commons-fileupload</group

  • 使用jQuery.form.js/springmvc框架实现文件上传功能

    使用的技术有jquery.form.js框架, 以及springmvc框架.主要实现异步文件上传的同时封装对象,以及一些注意事项. 功能本身是很简单的,但是涉及到一些传递参数类型的问题.例如:jquery的ajax方法与jquery.form.js中的ajaxSubmit方法的参数,具体细节将在下一篇博客中分享. 重点: html表格三要素: action="fileUpload/fileUpload" method="post" enctype="mul

随机推荐