在实际开发中,经常遇到要实现文件上传到服务器端的功能。Spring可以继承commons-fileupload插件来实现文件上传的功能。分为前端JSP编写和后台Controller的编写。
前期准备工作,首先要引入commons-fileupload这个jar包,pom.xml中的配置如下:
<!-- 实现文件上传,spring集成了这个功能 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
然后配置拦截器,在dispatcher-servlet.xml中添加
<!-- 实现文件上传,这样一旦某个Request是一个MultipartRequest,它就会首先被MultipartResolver处理,然后再转发相应的Controller -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为1MB -->
<property name="maxUploadSize">
<value>1048576</value>
</property>
</bean>
直接上代码:
1、前端JSP编写
upload.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="resources/js/jquery.js"></script>
</head>
<body>
<form method="post" action="upload.do" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
2、后台UploadController编写
package nju.software.xkxt.web.controller;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
* @author typ
*
*/
@Controller
public class UploadController {
/**
* 进入下载界面
*
* @param request
* @param response
* @param model
* @return
* @throws IOException
*/
@RequestMapping(value = "upload_enter.do", method = RequestMethod.GET)
public String enter(HttpServletRequest request,
HttpServletResponse response, ModelMap model) throws IOException {
// 进入下载界面
return "upload";
}
/**
* 具体的实现下载功能
*
* @param request
* @param response
* @param model
* @throws IOException
*/
@RequestMapping(value = "upload.do", method = RequestMethod.POST)
public void upload(HttpServletRequest request,
HttpServletResponse response, ModelMap model) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 得到上传的文件
MultipartFile mFile = multipartRequest.getFile("file");
// 得到上传服务器的路径
String path = request.getSession().getServletContext()
.getRealPath("/WEB-INF/upload/");
// 得到上传的文件的文件名
String filename = mFile.getOriginalFilename();
byte[] b = mFile.getBytes();
path += "\\" + filename;
// 文件流写到服务器端
FileOutputStream outputStream = new FileOutputStream(path);
outputStream.write(b);
inputStream.close();
outputStream.close();
}
}
这样就很容易的实现了文件上传的功能。