spring MVC 文件上传

本文介绍了一个使用Spring MVC框架实现文件上传的例子。通过展示HTML表单和Java控制器代码,详细说明了如何设置文件上传的前端界面及后端处理流程,并配置了文件的最大上传尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:http://apps.hi.baidu.com/share/detail/34190740

jsp页面:

<form action="upload.do" method="post" enctype="multipart/form-data">
    <table border="1">
    <tr>
    <td>名称:</td>
    <td><input type="text" id="name" name="name"></td>
    </tr>
    <tr>
    <td>路径</td>
    <td><input type="file" id="file" name="file"/></td>
    </tr>
    <tr>
    <td colspan="2"><input type="submit" value="上传"/></td>
    </tr>
    </table>
    </form>

----------------------------------------------------------------------------

public ModelAndView handleRequest(HttpServletRequest arg0,
   HttpServletResponse arg1) throws Exception {
   //转型为MultipartHttpRequest
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)arg0;
  //根据前台的name名称得到上传的文件
  MultipartFile file = multipartRequest.getFile("file");   
      // 获得文件名:   
      String  realFileName = file.getOriginalFilename();  
      System.out.println("获得文件名:"+realFileName);
      //获取路径
      String ctxPath = arg0.getContextPath();
      ctxPath = arg0.getSession().getServletContext().getRealPath("/")+"
\\"+"images\\";
      System.out.println("路径:"+ctxPath);
      // 创建文件
      File dirPath = new File(ctxPath);
      if(!dirPath.exists())
      {
       dirPath.mkdir();
      }
      File uploadFile = new File(ctxPath+realFileName);
      //
      FileCopyUtils.copy(file.getBytes(), uploadFile);


       return null;
 }

-----------------------------------------------------------------------

XML文件里配置上传文件的大小

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"/>
        <property name="maxInMemorySize" value="4096"/>
   </bean>

--------------------------------------------------------

切记要---添加commons-fileupload-1.2.jar,添加commons-io-1.3.1.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值