SpringMVC文件上传(一)

来源:互联网 发布:淘宝网达芙妮女凉鞋 编辑:程序博客网 时间:2024/06/01 09:44

从这一章节开始,我们将要实现用户可以上传自己的图片。不过,这里我们先实现简单的上传,后面我们还会讲到如何通过配置文件来实现指定上传文件的路径,当然还有文件的类型确定、文件大小、文件的错误处理等。

1.视图层实现

     现在我们需要在templates的路径下创建profile/uploadPage.html.

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"layout:decorator="layout/default"><head lang="en"><title>Profile Picture Upload</title></head><body><div class="row" layout:fragment="content"><h2 class="indigo-text center">Upload</h2><form th:action="@{/upload}" method="post" enctype="multipart/form-data" class="col m8 s12 offset-m2"><div class="input-field col s6"><input type="file" id="file" name="file"/></div><div class="col s6 center"><button class="btn indigo waves-effect waves-light"type="submit" name="save" th:text="#{submit}">Submit<i class="mdi-content-send right"></i></button></div></form></div></body></html>

2.控制层的实现

之后,我们需要处理的是控制层的相关逻辑。

package masterSpringMvc.profile;import org.apache.tomcat.util.http.fileupload.IOUtils;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@Controllerpublic class PictureUploadController {public static final Resource PICTURES_DIR = newFileSystemResource("./pictures");@RequestMapping("upload")public String uploadPage() {return "profile/uploadPage";}@RequestMapping(value = "/upload", method = RequestMethod.POST)public String onUpload(MultipartFile file) throws IOException {String filename = file.getOriginalFilename();File tempFile = File.createTempFile("pic",getFileExtension(filename), PICTURES_DIR.getFile());try (InputStream in = file.getInputStream();OutputStream out = new FileOutputStream(tempFile)) {IOUtils.copy(in, out);}return "profile/uploadPage";}private static String getFileExtension(String name) {return name.substring(name.lastIndexOf("."));}}

上在代码的一个地方就是要创建pictures的文件夹,这个文件夹是项目的根目录下。这个文件的上传,需要用户注入MultipartFile的接口的文件在控制层,MultipartFile接口现在这几个方法:获取上传文件的名称、文件的大小和文件所包含的内容。这里还有一个方法值得我们去注意的,那就是IOUtils.copy的方法,这个方法就是编写一个输入流到输出流的方法。

由于我们项目用JDK8所以我们的try()部分可以写成下面的形式:

 try (InputStream in = file.getInputStream();OutputStream out = new FileOutputStream(tempFile)) {IOUtils.copy(in, out);}

3.总结

这一节中,我们只是简单地实现了文件的上传,可是还有很从问题,比如 文件大小、不是图片的文件等。我们该如何去处理,这个将在下面的一节中讲解。这里我们上传文件后,在pictures的文件夹下可以看到下面的结果。


源码下载:git@github.com:owenwilliam/masterSpringMVC.git





0 0