关于SpringMVC上传文件的方法

1.配置applicationContext.xml文件

  1.  <!-- 支持上传文件 -->  
  2.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>  
2.jsp中支持上传 enctype = "multipart/form-data"

  1. <%@ page pageEncoding="utf-8"%>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5. <meta charset="utf-8">  
  6. <title>上传图片</title>  
  7. </head>  
  8. <body>  
  9. <form action="upload" method="post" enctype="multipart/form-data">  
  10. <input type="file" name="file" /> <input type="submit" value="Submit" /></form>  
  11. </body>  
  12. </html>  
3.controller层

  1. import java.io.File;  
  2. import java.util.Date;  
  3.   
  4. import javax.servlet.http.HttpServletRequest;  
  5.   
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.ModelMap;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestParam;  
  10. import org.springframework.web.multipart.MultipartFile;  
  11.   
  12. @Controller  
  13. public class UploadAction {  
  14.   
  15.     @RequestMapping(value = "/upload")  
  16.     public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  
  17.   
  18.         System.out.println("开始");
  19. //保存文件的路径,在项目的 upload 文件夹内 
  20.         String path = request.getSession().getServletContext().getRealPath("upload");  
  21.         String fileName = file.getOriginalFilename();  
  22. //        String fileName = new Date().getTime()+".jpg";  
  23.         File targetFile = new File(path, fileName);  
  24.         if(!targetFile.exists()){  
  25.             targetFile.mkdirs();  
  26.         }  
  27.         //保存  
  28.         try {  
  29.             file.transferTo(targetFile);  
  30.         } catch (Exception e) {  
  31.             e.printStackTrace();  
  32.         }
  33. //request.getContextPath()+"/upload/"+fileName  文件的保存路径,获取文件时用  
  34.         model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
  35.         return "result";  
  36.     }  
  37.   
  38. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值