1、添加文件上传依赖:
<!-- pom.xml -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、配置多媒体处理器:
<!-- config/spring/springmvc.xml -->
<!--
配置多媒体处理器
注意:这里的 id 必须使用 multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--限制单次文件上传大小不超过 8m-->
<property name="maxUploadSize" value="8388608"/>
</bean>
3、编写文件上传页面:
<!-- WEB-INF/jsp/fileupload.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>图片上传</title>
</head>
<body>
<form action="/fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="picFile">
<input type="submit" value="上传">
</form>
</body>
</html>
4、编写文件上传服务端代码:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class TestController {
@RequestMapping(value = "fileupload", method = RequestMethod.GET)
public String upload() {
return "fileupload";
}
@RequestMapping(value = "fileupload", method = RequestMethod.POST)
public String upload(Model model, MultipartFile picFile) throws IOException {
File file = new File("D:/upload/" + picFile.getOriginalFilename());
picFile.transferTo(file);
model.addAttribute("msg", "上传成功");
return "fileupload";
}
}
评论区