Spring MVC处理文件上传

Spring MVC处理文件上传 David发表在天码营 

Spring MVC处理文件上传也是蜻蜓点水轻松惬意,今天让我们简单的学习一下吧。

环境准备

  • 一个称手的文本编辑器(例如Vim、Emacs、Sublime Text)或者IDE(Eclipse、Idea Intellij)
  • Java环境(JDK 1.7或以上版本)
  • Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)

初始化Spring MVC应用代码

参考Spring MVC快速入门建立一个最简单的基于Spring Boot的Web应用。在处理文件的过程中涉及到输入输出流的操作,为此引入Guava库依赖:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>18.0</version>
</dependency>

创建@Controller处理文件上传请求

表单中添加的文件本质上也是表单中的一项,Spring使用MultipartFile类对它进行了封装:

import com.google.common.io.Files;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @RequestMapping(value="/upload", method= RequestMethod.GET)
    public String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            try {
                Files.write(file.getBytes(), new File(name));
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload because the file was empty.";
        }
    }
}

handleFileUpload()方法获取上传的文件对象后,需要先判断其是否为空,如果不为空方才通过Files.write()方法存储至文件系统。

文件上传配置

服务期程序处理用户上传的文件时,一个最重要的措施就是限制用户上传文件的大小,否则如果用户上传一个5GB大小的文件将会消耗巨大的服务器资源。使用Spring Boot框架,可以通过src/main/resources/application.properties轻松配置这些参数:

multipart.maxFileSize=32MB
multipart.maxRequestSize=32MB

maxFileSize限制的是总文件大小,maxRequestSize限制的是包含multipart/form-data表单数据的请求总大小,上述例子中都不能超过32MB,还可以使用KB, GB等单位进行配置。

文件上传表单

HTML中用户处理文件上传的输入框是<input type="file">

<html>
<body>
  <form method="POST" enctype="multipart/form-data"
    action="/upload">
    File to upload: <input type="file" name="file"><br /> <br />
    <input type="submit" value="Upload"> Press here to upload the file!
  </form>
</body>
</html>

需要注意的是,务必指定<form>enctype属性为multipart/form-data才能支持将本地文件上传到服务器。


更多文章请访问 天码营网站


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值