SpringMvc文件上传

1.导入相关架包    Fileupload

 

 2.  网页

表单必须是post提交,编码必须是multipart/form-data  文件上传文本框必须起名。

 

 

 3.在springmvc中配置文件上传解析器

 

 

4.在控制层处理代码

 1 public class UploadFilecontroller {
 2     @RequestMapping("file")                    //HttpServletRequest为了获取上传文件的路径
 3     public String upload(MultipartFile photo,HttpServletRequest request) {//MultipartFile photo:把上传的文件封装到MultipartFile中
 4         //1.获取文件上传的真实保存路径
 5         String realPath = request.getServletContext().getRealPath("/upload");
 6         System.out.println(realPath);
 7         //2.创建一个文件对象
 8         File file=new File(realPath);
 9         if(!file.exists()) {//如果该路径不存在
10             file.mkdirs();
11         }
12         //3.获取文件名
13         String name =System.currentTimeMillis()+ photo.getOriginalFilename();
14         
15         //新建文件对象
16         File targetFile=new File(realPath+"/"+name);
17         
18         try {
19             //4.把文件写入到指定的目录下
20             FileUtils.writeByteArrayToFile(targetFile, photo.getBytes());
21         } catch (IOException e) {
22             // TODO Auto-generated catch block
23             e.printStackTrace();
24         }
25         return "redirect:index.jsp";
26     }
27 }

 

转载于:https://www.cnblogs.com/mcl2238973568/p/11461621.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值