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="multipart/form-data">                      
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="uploadFile" id="uploadFile">
	</div>
</form>
  • 通过ajax发送文件上传请求
$.ajax({
       url: "${path }/upload",
       type: "POST",
       data: new FormData($("#saveUploadForm")[0]),
       processData: false,//告诉ajax不要处理和编码这些数据,直接提交
       contentType: false,//不使用默认的内容类型
       success: function (result) {
           layer.msg(result);
       },
       error: function (e) {
           layer.msg(e);
       }
   });

3、多文件上传

1):后台代码

 /**
   * 功能描述: <br>
   * 〈封装单个文件上传的方法〉
   *
   * @ClassName: Upload1Controller
   * @Author: hf
   * @Version: 1.0.0
   * @Date: 2018/02/14 10:24
   * @Param: [webPath 要上传的文件夹路径(webapp下), file 要上传的文件, session]
   * @return: void
   * 
   */
private String uploadFile(String webPath, MultipartFile file, HttpSession session) {
        ServletContext context = session.getServletContext();
        //获得真实路径
        String realPath = context.getRealPath(webPath);
        String fileName = UUID.randomUUID().toString().replace("-", "").substring(0, 15) + "_file_" + file.getOriginalFilename();
        try {
            File file1 = new File(realPath);
            if (!file1.exists()) {
                //目录不在创造目录
                file1.mkdirs();
            }
            file.transferTo(new File(realPath + "/" + fileName));
            //返回图片在服务器下的路径
            return webPath + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
 }


/**
  * 功能描述: <br>
  * 〈文件上传〉
  *
  * @ClassName: Upload1Controller
  * @Author: hf
  * @Version: 1.0.0
  * @Date: 2018/10/13 12:45
  * @Param: [file 文件数组,session]
  * @return: java.lang.Object
  * 
  */
 @RequestMapping("/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
 public Object upload(@RequestParam("file") MultipartFile[] file, HttpSession session) {
     for (int i = 0; i < file.length; i++) {
         MultipartFile multipartFile = file[i];
         String uploadFilePath = uploadFile("/upload", multipartFile, session);
         //输出返回结果
         System.out.println(uploadFilePath );
     }
     return "success";
 }

2):前端代码

  • 要提交的文件表单、enctype=“multipart/form-data”,属性必不可少
<form role="form" id="saveFileForm" enctype="multipart/form-data">                      
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="file">
	</div>
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="file">
	</div>
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="file">
	</div>
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="file">
	</div>
	<div class="form-group">
		<label>选择文件</label>
		<input type="file" class="form-control" name="file">
	</div>
</form>
  • 通过ajax发送文件上传请求
$.ajax({
    url: "${path }/upload",
    type: "POST",
    data: new FormData($("#saveFileForm")[0]),
    processData: false,//告诉ajax不要处理和编码这些数据,直接提交
    contentType: false,//不使用默认的内容类型
    success: function (result) {
        layer.msg(result);
    },
    error: function (e) {
        layer.msg(e);
    }
});

3):文件上传带进度条

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="${path}/static/plugin/jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="${path}/static/plugin/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${path}/static/plugin/layer-v3.1.1/layer/layer.js"></script>
<link rel="stylesheet" href="static/plugin/bootstrap-3.3.7/css/bootstrap.min.css">

<body>
<div class="container">
    <div class="row">
        <div class="col-sm-4"></div>
        <div class="col-sm-4">
            <form id="fileForm" enctype="multipart/form-data">
                <label>请选择文件:</label><input type="file" name="file">

            </form>
            <button id="submitBtn">上传</button>
            <br/>
            <div class="progress">
                <div class="progress-bar" role="progressbar"
                     style="width: 0%;">

                </div>
            </div>
        </div>
        <div class="col-sm-4"></div>
    </div>
</div>
<script type="text/javascript">
    //发送ajax请求:xhr对象发送请求
    $("#submitBtn").click(function () {
        $.ajax({
            url: "${path}/upload",
            data: new FormData($("#fileForm")[0]),
            processData: false,
            contentType: false,
            type: "POST",
            dataType: "text",
            xhr: function () {
                //获取xhr
                var xhr = $.ajaxSettings.xhr();
                //上传期间的回调函数、每隔xms触发一次
                xhr.upload.onprogress = function (ev) {
                    //获取当前上传了多少数据、总共是多少数据
                    console.log("已经上传:" + ev.loaded);
                    console.log("总计:" + ev.total);
                    console.log("当前进度:" + (ev.loaded / ev.total) * 100 + "%");
                    var procent = ((ev.loaded / ev.total) * 100).toFixed(2);
                    $(".progress-bar").css('width', procent + "%").text(procent + "%");
                };
                return xhr;
            },
            success: function (result) {
                layer.msg(result);
                $("#fileForm").reset;
            }
        });
    });
</script>
</body>
</html>
  • 效果图
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44187730/article/details/87254301