Spring MVC AJAX 方式图片上传,采用 base64 编码图片。

pom.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.2</version>
</dependency>

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.9</version>
</dependency>

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

注:如果使用了 Spring security,其中也有 Base64 类,可以不需要 commons-codec

applicationContext.xml

 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
<servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.html</url-pattern>
  <url-pattern>*.htm</url-pattern>
  <url-pattern>*.json</url-pattern>
  <url-pattern>*.xml</url-pattern>
</servlet-mapping>

<mvc:annotation-driven />

<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.mooc" />


<bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
    value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
    <property name="order" value="2" />
</bean>

<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="500000" />
</bean>

UploadController.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
@Controller
@RequestMapping(value = "upload")
public class UploadController {

  @RequestMapping(method = RequestMethod.GET)
  public String showUpload() {
    return "ajaxupload";
  }

  @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  public JsonLogo doUpload(@RequestParam("logo") MultipartFile logo,
      MultipartHttpServletRequest request) {
    try {
      JsonLogo jsonLogo = new JsonLogo();

      if (!logo.isEmpty()) {
        jsonLogo.setImage(new String(Base64.encodeBase64(logo
            .getBytes())));

        String logoPathDir = "/upload";
        String logoRealPathDir = request.getSession()
            .getServletContext().getRealPath(logoPathDir);
        File logoSaveFile = new File(logoRealPathDir);
        if (!logoSaveFile.exists())
          logoSaveFile.mkdirs();

        String suffix = logo.getOriginalFilename().substring(
            logo.getOriginalFilename().lastIndexOf("."));
        String logoImageName = String.valueOf(System
            .currentTimeMillis()) + suffix;
        String fileName = logoRealPathDir + File.separator
            + logoImageName;
        File file = new File(fileName);
        logo.transferTo(file);
      }

      return jsonLogo;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
}

JsonLogo.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class JsonLogo implements Serializable {
  private static final long serialVersionUID = 1165407268915529059L;
  
  @JsonProperty
  private String image;

  public String getImage() {
    return image;
  }

  public void setImage(String image) {
    this.image = image;
  }
}

ajaxupload.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
47
48
49
50
51
52
53
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8">
<script type="text/javascript" src="/resources/js/jquery.min.js"></script>
<title>Ajax Upload</title>
</head>
<body>

<form id="uploadLogoForm" enctype="multipart/form-data">
 
    <div>
    <label>Logo:</label>                
    <div id="imagePlaceHolder"></div>
    </div>
 
    <div>
    <label for="logo">Choose your logo:</label>
    <input id="logo" type="file" name="logo"/>
    </div>   

</form>

<button id="uploadLogoButton">Upload Logo</button>

</body>

<script>
  $(document).ready(function(){
    $('#uploadLogoButton').on('click', function () {
      var form = new FormData(document.getElementById('uploadLogoForm'));
      $.ajax({
        url: "upload.json",
        data: form,
        dataType: 'text',
        processData: false,
        contentType: false,
        type: 'POST',
        
        success: function (response) {
          var data = jQuery.parseJSON(response);   
          $('#imagePlaceHolder').html('<img src="data:image/jpg;base64,' + data.image + '"/>');   
        },
        error: function (jqXHR) {
          //Error handling
        }
      });
    });    
  });
</script>
</html>