初学SpringMVC,使用MVC进行文件上传

最近在做一个文件上传的功能,走了不少弯路,话不多说,直接上代码:

导入各种jar包,首先是applicationContext.xml配置文件中:

1 <!-- 配置文件解析器 -->
2       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
3     </bean>
View Code

写两个前端页面:upLoad.jsp

1 <body>
2     <form action="upload.do" method="post" enctype="multipart/form-data">
3           姓名:<input type="text" name="username"/><br>
4           头像:<input type="file" name="mf"/><br>
5           姓名:<input type="submit" value="上传"/>
6     </form>
7 </body>
View Code

show.jsp

1 <body>
2      <h1>head image</h1>
3      <img alt="" src="${image }" style="width: 400px;height: 500px">
4 </body>
View Code

然后进入正题,写一个上传的战士页面的controller

@RequestMapping("/toUpload.do")  //SpringMVC的映射标注
    public String toUpload(){
        return "upload";
    }

然后

 1 @Controller
 2 public class FileUploadController { // MultipartFile 用于接受文件对象
 3     @RequestMapping("/upload.do") // MultipartFile用于接受用户名和数据,否则文件上传时候也上encytype后悔接收不到数据
 4     public String upload(String username, MultipartFile mf, HttpServletRequest req) {
 5 
 6         System.out.println(username + "||" + mf.getOriginalFilename() + "||" + mf.getSize());
 7         // 把文件写入响应路径下
 8         String realpath = req.getServletContext().getRealPath("images");// 获取到当前文件夹的真是路径
 9         String orName = mf.getOriginalFilename();// 获取文件的原始名字
10         String fileName = System.currentTimeMillis() + orName.substring(orName.lastIndexOf("."));// 修改上传文件的名字,时间加后缀
11         String filePath = realpath + "/" + fileName;
12         System.out.println(filePath);
13         File file = new File(filePath);// 创建一个文件对象
14         try {
15             mf.transferTo(file);// 将文件写入到路径中
16         } catch (IllegalStateException e) {
17             e.printStackTrace();
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21         req.setAttribute("image", "images/" + fileName);
22         return "show";
23     }
24 }
View Code

OK!,大功告成!

转载于:https://www.cnblogs.com/hx1098/p/9326035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值