springmvc+ajax異步上傳圖片


1、javaweb傳統的上傳圖片方式就是通過form表單提交

<form action="#" method="post" enctype="multipart/form-data">
    <input type="file" name="file"> 
    <input type="submit" value="上傳">
</form>

 

2、現在想要實現:點擊文件表單的"瀏覽"按鈕后,文件異步上傳,然后返回文件的路徑,頁面實時刷新顯示剛才上傳的圖片。

  2.1、新建一個springboot項目picDemo

  

  pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

 

  application.properties

server.port=8090
server.servlet.context-path=/

 

  2.2、要實現圖片異步上傳,可以使用jquery.form.js插件。

  save.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>標題</title>
<script type="text/javascript" th:src="@{/js/jquery.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery.form.js}"></script>
<style type="text/css">
.hidden {
    display:none;
}
</style>
</head>
<body>

<div id="film_save">
<form id="form" action="#" th:action="@{/film/save}" method="post" th:object="${film}" enctype="multipart/form-data">
    <input type="hidden" name="id" th:value="*{id}"/>

    <table class="table">
        <tr>
            <td>電影名稱:</td>
            <td><input type="text" name="name" th:value="*{name}"/></td>
        </tr>
        <tr>
            <td>電影圖片:</td>
            <td><input type="file" name="file" id="file" onchange="fileUpload()"/></td>
        </tr>
        <tr>
            <td><input type="hidden" id="imageUrl" name="imageUrl" value=""/></td>
            <td><img id="imgSrc" th:class="${film.imageUrl eq null or film.imageUrl eq ''}?hidden:''" th:src="'http://localhost:8080/image/' + ${film.imageUrl}" style="width:200px;"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="保存"/></td>
        </tr>
    </table>
</form>
    
<script type="text/javascript">
    function fileUpload() {
        var option = {
            type:'POST',
            url:'/film/uploadPic',
            dataType:'json',
            data:{
                fileName : 'file'
            },
            success:function(data){
                //把json串轉換成json對象
                //var jsonObj = $.parseJSON(data);
                //alert(data);
            
                //返回服務器圖片路徑,把圖片路徑設置給img標簽
                $("#imgSrc").attr("src",data.fullPath);
                
                // 顯示圖片
                $("#imgSrc").removeClass("hidden");
                
                //數據庫保存相對路徑
                $("#imageUrl").val(data.relativePath);
                //alert($("#imageUrl").val());
            }    
        };
        
        $("#form").ajaxSubmit(option);
    }
</script>
</div>
</body>
</html>

 

  2.3、后端代碼

   IndexController

package com.oy;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class IndexController {

    @RequestMapping("/save")
    public Object save(Film film) {
        return "save";
    }
    
    @RequestMapping("/film/uploadPic")
    @ResponseBody
    public Object uploadPic(MultipartFile file) throws Exception {
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase() 
                + "_" + oldName;
        System.out.println("上傳的圖片的newName: " + newName);
        
        File base = new File("d:/image/filmImage/");
        if (! base.exists()) {
            base.mkdirs();
        }
        
        // 保存文件
        file.transferTo(new File("d:/image/filmImage/" + newName));
        
        // 封裝返回結果
        Map<String, Object> map = new HashMap<>();
        map.put("fullPath", "http://localhost:8090/image/" + newName);
        map.put("relativePath", newName);
        
        return map;
    }
}

 

  Film類:

public class Film {
    private Integer id; // 編號
    private String name; // 電影名稱
    private String imageUrl; // 電影圖片

    // getter和setter方法省略
}

 

  圖片上傳后,java返回的json數據為:

{
    "fullPath": "http://localhost:8090/image/E29C543179AD4B69B521EB542D9E735E_無標題.png",
    "relativePath": "E29C543179AD4B69B521EB542D9E735E_無標題.png"
}

  其中,fullPath為圖片全路徑。要實現圖片上傳后,圖片刷新顯示,還要再springboot中配置圖片保存目錄的路徑映射:

  WebConfigurer類

package com.oy;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**").addResourceLocations("file:D:/image/filmImage/");
    }
}

 

3、其他

  3.1、上面的demo是將圖片保存目錄的路徑進行了映射。圖片url與demo是在同一個域,都是http://localhost:8090,其實圖片可以配置成其他的,比如http://localhost:8091,然后用外置的tomcat(非springboot內置)或nginx配置映射。

  3.2、將圖片上傳至圖片服務器(分布式文件系統)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM