hooyantsing's Blog

第117次课程_Spring_MVC框架整合

字数统计: 1.2k阅读时长: 6 min
2020/03/03

源辰76班

第117次课程

2020.03.03

内容

Spring_MVC框架整合

项目路径:

1.Spring文件上传

1.1表单提交

以往两种上传技术:

1.smartupload(淘汰,不推荐,存在乱码问题等)。

2.web.xml version=”3.1” 支持的方式,详见”第102次课程 复习3_Web项目”。

导入依赖

pom.xml

1
2
3
4
5
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
</dependency>

加入Spring配置

beans.xml

1
2
3
4
5
6
<!-- 定义 文件上传解析器 -->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <!-- one of the properties available; the  maximum file size in bytes -->
      <property name="maxUploadSize" value="100000" />
</bean>

upload.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
    <head>
        <title>Upload a file please</title>
    </head>
    <body>
        <h1>Please upload a file</h1>
        <form method="post" action="upload.do"  enctype="multipart/form-data">
            <input type="text" name="name"/>
            <input type="file" name="file"/>
            <input type="file" name="file1"/>
            <input type="file" name="file2"/>
            <input type="submit"/>
        </form>
    </body>
</html>

UploadAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.yc.springmvc.web.d0303;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.PostMapping;
import  org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadAction {
    //需要做属性名的映射
    //前端 属性name 对应后端 形参
    @PostMapping("upload.do")
    public String handleFormUpload(@RequestParam("name")  String name,
            @RequestParam("file") MultipartFile file)  throws IllegalStateException, IOException {
        
        //判断前端有文件上传
        if (!file.isEmpty()) {
            /*
             * 返回上传流
             * 平时不用,有更好的
             */
          //file.getInputStream();
          
          //获取表单内的name
          file.getName();
          //获取文件名
          String filename = file.getOriginalFilename();
          //获取文件大小
          file.getSize();
          
          File diskFile = new File("E:\\ba2",filename);
          file.transferTo(diskFile);
          
          return "success";
        }
        return "redirect:upload.html";
    }
}

1.2AJAX提交

知识点:单input多图片上传,访问webapp以外的资源,后端返回json格式


将后端返回的数据都以json格式返回的依赖

pom.xml

1
2
3
4
5
6
7
<!-- 控制器Action 返回json数据 -->
<!--  https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
</dependency>

访问webapp以外的资源

作用:将上传到服务器的资源,放置在服务器路径之外。可以应用于web服务器和file服务器分离等。

beans.xml

1
2
3
4
5
6
<!-- webapp以外文件获取方式:映射标签 -->
<!--
          location:映射的真实路径
          mapping:映射的web路径
-->
<mvc:resources location="file:/E:/ba2/"  mapping="/ba2/**"></mvc:resources>

UploadAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.yc.springmvc.web.d0303;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.GetMapping;
import  org.springframework.web.bind.annotation.PostMapping;
import  org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadAction {
     @PostMapping("upload.do")
    public String handleFormUpload(@RequestParam("name")  String name,
            @RequestParam("file") MultipartFile  file,@RequestParam("file1") MultipartFile file1) throws  IllegalStateException, IOException {
        if (!file.isEmpty()) {
            /*
             * 返回上传流
             * 平时不用,有更好的
             */
          //file.getInputStream();
          
          //获取表单内的name
          file.getName();
          //获取文件名
          String filename = file.getOriginalFilename();
          //获取文件大小
          file.getSize();
          
          File diskFile = new File("E:\\ba2",filename);
          file.transferTo(diskFile);
          
          return "success";
        }
        return "redirect:upload.html";
    }
     
     @GetMapping("upload.html")
     public String toupload() {
          return "upload";
     }
     
     @ResponseBody
     @PostMapping("upload_ajax.do")
     public List<String>  handleFormUpload1(@RequestParam("name") String name,
              @RequestParam("file") MultipartFile[] files  )
              throws IllegalStateException, IOException {     
          List<String> ret = new ArrayList<String>();
          for(MultipartFile file : files) {
              if (!file.isEmpty()) {
                   String filename =  file.getOriginalFilename(); // ===> 提交的文件名
                   File diskFile = new File("E:/ba2/",  filename);  // ???????
                   file.transferTo(diskFile);  // 保存文件
                   ret.add("ba2/" + filename);
              }
          }
          System.out.println(ret.toString());
          return ret;
     }
}

upload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<%@ page language="java" contentType="text/html;  charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;  charset=utf-8">
<title>Insert title here</title>
<style type="text/css">
     img{
          width: 300px;
     }
</style>
</head>
<script type="text/javascript"  src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
     function uploadImgs(){
          //FormData抓取整张表单数据
          var formData = new FormData(ff);
          $.ajax({
              type : "POST",
              url : 'upload_ajax.do',
              data : formData,
              processData : false,
              contentType : false,
              success : function(data){
                   img1.src = data[0];
                   img2.src = data[1];
                   img3.src = data[2];
              }
          });
     }    
</script>
<body>
     <h1>Please upload a file</h1>
        <form id="ff" method="post" action="upload.do"  enctype="multipart/form-data">
            <input type="text" name="name"/>
            <input type="file" name="file"  multiple="multiple"/>            
            <input type="submit" value="表单文件上传"/>
            <input type="button" value="AJAX文件上传"  onclick="uploadImgs()">
        </form>
        
        <img id="img1" alt="" src="">
        <img id="img2" alt="" src="">
        <img id="img3" alt="" src="">
</body>
</html>
CATALOG