在实际开发中,经常遇到要实现文件上传到服务器端的功能。Spring可以继承commons-fileupload插件来实现文件上传的功能。分为前端JSP编写和后台Controller的编写。
前期准备工作,首先要引入commons-fileupload这个jar包,pom.xml中的配置如下:
1、前端JSP编写
upload.jsp
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();
InputStream inputStream = mFile.getInputStream();
byte[] b = new byte[1048576];
int length = inputStream.read(b);
path += "\\" + filename;
// 文件流写到服务器端
FileOutputStream outputStream = new FileOutputStream(path);
outputStream.write(b, 0, length);
inputStream.close();
outputStream.close();
}
}