1. 程式人生 > >SpringBoot使用者上傳圖片與回顯

SpringBoot使用者上傳圖片與回顯

  • 現在的時間:2018-10-27
  • 最近在做的一個東西要顯示使用者上傳的圖片,以前使用獨立的tomcat時是很容易的一件事,但SpringBoot使用整合的tomcat,所以需要配置一下。

基本思路

  • 專案較小,不使用獨立的檔案伺服器,直接將圖片存在伺服器的磁碟上,資料庫存放圖片在伺服器上的絕對路徑。
  • 但在顯示圖片時<img src=“xxx”/>標籤的src屬性不能直接使用從資料庫中取出來的絕對路徑,那樣圖片會顯示不出來。
  • 為了簡化問題這個demo中暫不使用資料庫也不對圖片的名字進行隨機化處理。

準備工作

  • 在springboot的全域性配置檔案中增加以下配置:cbs.imagesPath=file:/media/root/MyDisk/download/abcde/
  • file:後面是磁碟中的目錄,最後必須要有一個"/"號,我是目錄是如上所示。
  • 新增Thymeleaf依賴

上傳圖片

上傳頁面 index.html (這個頁面直接提交給一個controller,在controller中將圖片存到磁碟中)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>上傳頭像</title>
    </head>

    <body>
        <form action="/fileUploadController" method="post" enctype="multipart/form-data">
            上傳頭像:<input type="file" name="filename"/><br/><br/>
            <input type="submit" value="確定"/>
        </form>
    </body>
</html>

存入圖片的控制器

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;

@Controller
public class TestController
{
    @Value("${cbs.imagesPath}")
    private String theSetDir; //全域性配置檔案中設定的圖片的路徑

    @GetMapping("/{page}")
    public String toPate(@PathVariable("page") String page)
    {
        return page;
    }

    @RequestMapping(value = "/fileUploadController")
    public String fileUpload(MultipartFile filename, Model model) throws Exception
    {
        String parentDirPath = theSetDir.substring(theSetDir.indexOf(':')+1, theSetDir.length()); //通過設定的那個字串獲得存放圖片的目錄路徑
        String fileName = filename.getOriginalFilename();

        File parentDir = new File(parentDirPath);
        if(!parentDir.exists()) //如果那個目錄不存在先建立目錄
        {
            parentDir.mkdir();
        }

        filename.transferTo(new File(parentDirPath + fileName)); //全域性配置檔案中配置的目錄加上檔名

        model.addAttribute("pic_name", fileName);

        return "show";
    }
}

顯示圖片

增加一個配置類 不需要知道這個配置類具體是怎樣實現的,只需要知道這樣配置後有如下效果:上傳到cbs.imagesPath配置的目錄中的圖片,在專案中可以訪問,訪問是時標籤的src屬性的屬性值是"/images/圖片名.副檔名"。

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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 WebAppConfig implements WebMvcConfigurer
{

    @Value("${cbs.imagesPath}")
    private String mImagesPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        if (mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}"))
        {
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            if (imagesPath.indexOf(".jar") > 0)
            {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }
            else if (imagesPath.indexOf("classes") > 0)
            {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            mImagesPath = imagesPath;
        }
        LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath=" + mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
    }
}

顯示圖片的頁面 show.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>上傳的圖片</title>
    </head>

    <body>
        上傳的圖片:
        <img th:src="@{'/images/' + ${pic_name}}"/> <!--/images/xxx.xxx-->
    </body>
</html>

效果

上傳頁面: 選擇圖片: 點選上傳頁面的確定按鈕後:

下載這個demo

碼雲:https://gitee.com/sacredness/SpringBoot-ShowPic