核心代码:
`package controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class UserinfoController {
@RequestMapping(value = "upload")
public String loginMethod(@RequestParam String username, @RequestParam MultipartFile uploadFile,
HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("username=" + username);
String uploadFileName = uploadFile.getOriginalFilename();
System.out.println("文件名" + uploadFileName);
InputStream fileStream = uploadFile.getInputStream();
String uploadPath = request.getSession().getServletContext().getRealPath("/upload");
File destination = new File(uploadPath, uploadFileName);
FileUtils.copyInputStreamToFile(fileStream, destination);
return "index.jsp";
}
}
`
index.jsp
`<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="upload.spring" method="post" enctype="multipart/form-data">
username:<input type="text" name="username"><br />
需要上传的文件:<input type="file" name="uploadFile"><br />
<input type="submit" value="开始上传"><br />
</form>
</html>`
注意:使用此写法时
@RequestParam MultipartFile uploadFile
一定要注意前台<input type="file" name="uploadFile">
文件域的name名称一定要和参数名称uploadFile一样。还有必须在MultipartFile uploadFile对象前要加@RequestParam注解,不加会出现以下异常。
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.multipart.MultipartFile]: Specified class is an interface
推荐文章:Spring4 MVC单文件上传-写法1:
- 邮箱:ithelei@sina.cn
- 技术讨论群:687856230
- GoodLuck