SpringBoot+ajax+formData實現圖片上傳和回顯


前端Html

<h2>圖片上傳</h2>
<img src="" id="preview_photo" width="200px" height="200px">
<a href="javascript:void(0)" id="photo_upload" onclick="upLoadPhoto()">select photo</a>
<input type="file" id="upload" style="display: none" onchange="upload()">

注意 img標簽的src是未賦值的

js代碼

<script>
    function upLoadPhoto(){
        $("#upload").click();
    }
    function upload(){
        var form = new FormData();
        form.append("file", $("#upload")[0].files[0]);
        $.ajax({
            type :"POST",
            url:"http://localhost:8888/picture/upload.json",
            dataType:"json",
            data:form,
            processData:false,
            contentType:false,
            success:function(data){
                console.info(data.result.path);
                $("#preview_photo").attr("src",data.result.path);
            },
            error:function (data) {
                alert("error");
            }
        })
    }
</script>

這里推薦了解一下ajax的各個參數用處:

https://www.cnblogs.com/wuchenfei/p/9820958.html(借用大佬的博客)

后端這里沒有使用service,直接在controller中進行的fileName拼裝和返回

package com.zdj.controller;

import com.zdj.utils.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/picture")
public class PictureController {
    //圖片的物理存儲路徑
    private static final String filePath = "D:/aaaaa/";
    //設置的tomcat靜態虛擬路徑
    private static final String vFilePath = "http://localhost:8888/pic/";
    @RequestMapping("/upload")
    public R upLoad(@RequestParam("file") MultipartFile file[]){
        //獲取圖片的名字
        String fileName = file[0].getOriginalFilename();
        //獲取文件后綴名
        String suffix = getSuffix(fileName);
        //判斷后綴名
        if(!suffix.equals("jpg") && !suffix.equals("png")){
            System.out.println("suffix error");
            return R.ok("0");
        }
        //返回map來獲取圖片的虛擬路徑
        Map<String, String> result = new HashMap<>();
        //date文件夾,方便管理
        String dateFile = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newfileName = filePath + dateFile;
        File newFile = new File(newfileName);
        //判斷文件夾是否存在,不存在則創建
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        //為文件添加uuid防止名字重復
        fileName = UUID.randomUUID().toString().replace("-","") + fileName;
        String newFilePath = newfileName + "/" + fileName;
        result.put("path",vFilePath + dateFile + "/" + fileName);
        try {
            file[0].transferTo(new File(newFilePath));
        } catch (IllegalStateException|IOException e) {
            e.printStackTrace();
        }
        return R.ok(result);
    }
    //封裝獲取后綴名方法
    public static String getSuffix(String fileName){
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf + 1);
        return suffix;
    }
}

 

 當我寫到這里的時候我發現我卡住了,原因是回顯的時候無法直接從D盤中獲取圖片的路徑。

所以我使用了tomcat的虛擬路徑,在SpringBoot中添加config類

package com.zdj.config;

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 WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pic/**").addResourceLocations("file:D:/aaaaa/");
    }

}

 

同時這里的“D:/aaaaa/”直接被替換成了“http://localhost:8888/pic/”

前端獲取的虛擬路徑就可以直接賦給img標簽的src來進行圖片的回顯

 

 問題

1.@RequestParam("file")的使用

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

對於上述的圖片數據庫的補充:

添加文件大小的限制:1.前端限制,將這個問題交給用戶來解決 2. 后端限制,防止接口的惡意調用

主要針對后端的限制,方法體增加

@RestController
@RequestMapping("/picture")
public class PictureController {
    //圖片的物理存儲路徑
    private static final String filePath = "D:/aaaaa/";
    //設置的tomcat靜態虛擬路徑
    private static final String vFilePath = "http://localhost:8888/pic/";
    @RequestMapping("/upload")
    public R upLoad(@RequestParam("file") MultipartFile file){
        //對圖片大小進行限制(10M)
        if(!checkFileSize(file.getSize(), 10, "M")){
            return R.ok("error");
        }
        //獲取圖片的名字
        String fileName = file.getOriginalFilename();
        //獲取文件后綴名
        String suffix = getSuffix(fileName);
        //判斷后綴名
        if(!suffix.equals("jpg") && !suffix.equals("png")){
            System.out.println("suffix error");
            return R.ok("0");
        }
        //返回map來獲取圖片的虛擬路徑
        Map<String, String> result = new HashMap<>();
        //date文件夾,方便管理
        String dateFile = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newfileName = filePath + dateFile;
        File newFile = new File(newfileName);
        //判斷文件夾是否存在,不存在則創建
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        //為文件添加uuid防止名字重復
        fileName = UUID.randomUUID().toString().replace("-","") + fileName;
        String newFilePath = newfileName + "/" + fileName;
        result.put("path",vFilePath + dateFile + "/" + fileName);
        try {
            file.transferTo(new File(newFilePath));
        } catch (IllegalStateException|IOException e) {
            e.printStackTrace();
        }
        return R.ok(result);
    }
    //封裝獲取后綴名方法
    public static String getSuffix(String fileName){
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf + 1);
        return suffix;
    }

    /**
     *封裝判斷文件大小
     * @param len 文件長度默認單位字節
     * @param size 額定長度
     * @param unit 額定單位
     * @return
     */
    public static boolean checkFileSize(Long len, int size,  String unit){
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}

 


免責聲明!

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



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