SSM下的Java上传文件

SSM环境下的Java上传文件

  1. 通过MultipartFile类上传文件。
  2. 步骤:

    • a.SpringMvc中加入配置
       
      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <!--设置上传最大尺寸为1MB-->
      <property name="maxUploadSize" value="1048576"/>
      <property name="maxInMemorySize" value="5242880"/>
      <property name="defaultEncoding" value="UTF-8"/>
      <property name="resolveLazily" value="true"/>
      </bean>
      <--文件超过大小后异常的处理(此时出现的异常不会到Controller中)-->
      <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
      <props>
      <!-- 绕过了前端的大小限制,跳转到error.jsp页面 -->
      <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">redirect:/error.jsp
      </props>
      </property>
      </bean>

    • b.
       
      @RequestMapping(value = "/image", method=RequestMethod.POST)
      public Result uploadImage(HttpServletRequest request, @RequestParam("file")MultipartFile file){//file参数为web前台的name属性值
      String name = file.getName();
      System.out.println(name);//得到的是file
      String originalFilename = file.getOriginalFilename();
      System.out.println(originalFilename);//得到上传的文件名全称
      File file2 = new File("E:\1234.txt");
      try {
      file.transferTo(file2);//将文件保存到硬盘
      } catch (IllegalStateException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }
      result.setState(1);
      return result;
      }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值