您的位置:首页 > 编程语言 > Java开发

Spring MVC 的高级配置 - 文件上传配置

2017-09-22 00:00 411 查看
文件上传是一个项目里经常要用的功能, Spring MVC 通过配置一个MultipartResolver 来上传文件。
在Spring 的控制器中,通过MultipartFile file 来接收文件,通过MultipartFile[] files 接收多个文件上传。

(1) 添加文件上传依赖。

<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload}</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${common.io.version}</version>
</dependency>


(2)上传页面。在src/main/resources/views 下新建upload.jsp 。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="UTF-8">
<title>upload page</title>
</head>
<body>
<div class="upload">
<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/><br>
<input type="submit" value="上传">
</form>
</div>
</body>
</html>


(3) 添加转向到upload 页面的ViewController。

/**
* 配置中重写addViewControllers来简化配置
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("/index");
registry.addViewController("/error").setViewName("/error");
registry.addViewController("/toUpload").setViewName("/upload");
}


(4) MultipartResolver 配置。

/**
* 文件上传表单的视图解析器
*/
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
multipartResolver.setDefaultEncoding("UTF-8");
return multipartResolver;
}


(5) 控制器。

package com.discry.springboot_in_action.ch4_4;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class UploadController {

@RequestMapping(value="/upload",method = RequestMethod.POST)
public @ResponseBody String upload(MultipartFile file){//使用MultipartFile file 接受上传的文件。
try {
//使用FileUtils. writeByteArrayToFile 快速写文件到磁盘
FileUtils.writeByteArrayToFile(new File("e:/upload/"+file.getOriginalFilename()),file.getBytes());
return "ok";
}catch (Exception ex){
ex.printStackTrace();
return "error";
}
}
}


(6) 运行结果





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息