您的位置:首页 > 编程语言 > Java开发

java 上传文件的处理(MultipartFile file)

2017-10-27 10:30 471 查看
jsp页面

<%@page language="java" pageEncoding="UTF-8"%>

<div style="" id="importFormBox">

  <form target="importUploadFrame"enctype="multipart/form-data" method="post" action="messagetemplate/check_import" id="importForm" >

         

    <div class="inputfield">请选择您要导入的文件:

      <input type="file" size="22" name="file" />

       <button class="button" style="padding: 1px 1px;" type="submit">开始导入</button>

    </div>

    <div style="display: none;" class="progress"></div>

  </form>

  <div class="import_error_msg" style="display:none">

  </div>

  <div>

  <iframe frameborder="0" scrolling="no" name="importUploadFrame" src="about:blank"></iframe>

  </div>

</div>

java代码

@RequestMapping( value = "/check_import", method = RequestMethod.POST, produces = "text/plain; charset=UTF-8" )

  @ResponseBody

  public String do_check_import( HttpServletRequest request,MultipartFile file ) throws Exception

  {

    Operator currentOperator = this.getCurrentOperator( request.getSession() );

    try

    {

      String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  + file.getOriginalFilename();  

      System.out.println( filePath );

      // 转存文件  

      file.transferTo(new File(filePath));  

     

     Map<String, Object> ret = new HashMap<>();

    ret.put( "status", "ok" );

    ret.put( "data", data );

    return JSON.toJSONString( ret );

    }

    catch( Exception e )

    {

      Map<String, Object> ret = new HashMap<>();

    ret.put( "status", "ok" );

    ret.put( "data", data );

    return JSON.toJSONString( e.getMessage() );

    }

  }

配置 servlet-context.xml(如果没有这个配置,获取的文件是空的)

   

 <!-- 上传文件 -->  

  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  

    <property name="defaultEncoding" value="utf-8"/>  

    <!-- 最大内存大小 -->  

    <property name="maxInMemorySize" value="10240"/>  

    <!-- 最大文件大小,-1为不限制大小 -->  

    <property name="maxUploadSize" value="102400000"/>  

  </bean>

配置 pom.xml

 <dependency>  

      <groupId>commons-fileupload</groupId>  

      <artifactId>commons-fileupload</artifactId>  

      <version>1.3.3</version>  

    </dependency>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java