1.添加依赖
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.配置文件上传解析器
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
3.index.jsp
<form action="/account/upload" method="post" enctype="multipart/form-data">
文件: <input type="file" name="upload"></input>
<input type="submit" value="提交">
</form>
4.测试
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/upload")
public String upload(MultipartFile img , HttpServletRequest request, Model model) throws IOException {
//1.获取要上传的文件目录
String realPath = request.getSession().getServletContext().getRealPath("/upload");
//2.根据文件上传的目录创建File对象,如果不存在则创建1个File对象
File file = new File(realPath);
if (!file.exists()){
//创建一个file对象
file.mkdirs();
}
//获取文件上传名称
String fileName= img.getOriginalFilename();
//3.完成文件上传
img.transferTo(new File(realPath,fileName));
model.addAttribute("msg","你好,Spring MVC");
return "success";
}
}
5.结果:
6.总结:
文件上传
1、pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、配置上传解析器
<!–配置文件上传解析器–>
<bean id=”multipartResolver”
class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=”maxUploadSize” value=”5242880″ />
<property name=”defaultEncoding” value=”UTF-8″ />
</bean>
3、form
<form action=”/account/upload” method=”post” enctype=”multipart/form-data”>
图片:<input type=”file” name=”img”><br>
<input type=”submit” value=”上传”>
</form>
3、文件上传
@RequestMapping(“/upload”)
public String upload(MultipartFile img) throws IOException {
//1、获得tomcat的路径
//2、创建uploads目录
//3、上传文件
}
原文地址:https://blog.csdn.net/qq_62965575/article/details/135502639
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_54993.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!