SSM框架中实现多文件以及单文件上传

1、准备工作

1): 在pom.xml添加需要的依赖

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.5</version>
</dependency>
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.2</version>
</dependency>

2):在spring-mvc.xml配置文件解析器

  <!-- 配置文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!--设置默认编码-->
        <property name="defaultEncoding" value="utf-8"/>

        <!--设定文件上传最大值为50MB-->
        <property name="maxUploadSize" value="52428800"/>
    </bean>

2、单文件上传

1):后台代码

/**
   * 功能描述: <br>
   * 〈文件上传〉
   *
   * @ClassName: UploadController
   * @Author: hf
   * @Version: 1.0.0
   * @Date: 2019/02/14 9:55
   * @Param: [session 获取文件夹绝对路径, file 上传的文件]
   * @return: java.lang.Object
   * 
   */
  @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
  public Object upload(HttpSession session, @RequestParam("uploadFile") MultipartFile file) {
   
      //标识是否上传成功
      boolean bool = false;
     //获取要上传的目标文件夹绝对路径、webapp下
      ServletContext context = session.getServletContext();
      String realPath = context.getRealPath("/upload");

      //重新定义文件名、避免名称重复
      String fileName = UUID.randomUUID().toString().replace("-", "").substring(0, 15) + "_file_" + file.getOriginalFilename();
      try {
   
          //上传文件至指定位置
          file.transferTo(new File(realPath + "/" + fileName));
          bool=true;
      } catch (IOException e) {
   
          e.printStackTrace();
      }
      return bool ? "success" : "fail";
  }

2):前端代码

  • 要上传的文件表单、enctype=“multipart/form-data”,属性必不可少
<form role="form" id="saveUploadForm" enctype
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值