springMVC文件上传

1.导入需要的jar包(fileupload,commons-io)

 

 

 

2.网页表单提交格式post,编码要enctype="multipart/form-data",上传文件要有name

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>register</title>

</head>

<body>

<form action="/SpringMVC/user/register" method="post" enctype="multipart/form-data">

       name:<input type="text" name="name"/><br/>

       password:<input type="password" name="password"/><br/>

       phone:<input type="text" name="phone"/><br/>

       age:<input type="text" name="age"/><br/>

       photo:<input type="file" name="photo"/><br/>

       <input type="submit" value="提交"/><br/>

</form>

</body>

</html>

3.在Controller里处理

 

       @RequestMapping("register")

       public ModelAndView register(User user,MultipartFile phot,HttpServletRequest request) {

              ModelAndView mv=new ModelAndView("register");

              //1.通过request获取文件真实上传路径

              String pathname=request.getServletContext().getRealPath("/photo");

              //2.通过真实路径创建文件

              File file=new File(pathname);

              if(!file.exists()) {//判断是否存在,若不存在则新建

                     file.mkdirs();

              }

              //3.通过MultipartFile对象获取文件名

              String fileName=phot.getOriginalFilename();

              user.setPhoto(fileName);

              File targetFile=new File(pathname+"/"+fileName);

             

              try {

                     //4.通过FileUtils把MultipartFile的文件复制到目标文件

                     FileUtils.writeByteArrayToFile(targetFile, phot.getBytes());

              } catch (IOException e) {

                     e.printStackTrace();

              }

              request.setAttribute("user", user);

              return mv;

       }

4.在springMVC中配置文件上传解析器

         <!-- 配置文件上传解析器 -->

         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

                   <!-- 设置最大文件字节 -->

                   <property name="maxInMemorySize" value="200000"></property>

         </bean>

 

注意:网页上传文件的name要和实体类中放文件路径的属性不一样否则会报错

 

转载于:https://www.cnblogs.com/kfsrex/p/11461914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值