分享

spring MVC 文件上传

 IT技术武馆 2014-06-25

原文链接: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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约