SpringBoot中通過重寫WebMvcConfigurer的方法配置靜態資源映射實現圖片上傳后返回網絡Url


場景

前端調用上傳照片的功能,將某照片上傳到服務器上某磁盤路徑下,然后將通過靜態資源映射,將在服務器上

訪問的地址存儲到數據庫中,這樣在需要獲取這種照片的時候就能通過服務器上的url來獲取和顯示這張照片。

若依前后端分離版本地搭建開發環境並運行項目的教程:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

在此基礎上搭建起來前后端分離的項目,然后使用若依的通用的上傳接口實現圖片的上傳。

關於圖片的上傳的前端以及全流程可以參照:

SpringBoot+El-upload實現上傳文件到通用上傳接口並返回文件全路徑(若依前后端分離版源碼分析):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108383134

這里重點講后台的配置。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

首先圖片上傳的通用接口,首先新建通用上傳文件的接口

/**
 * 通用文件上傳下載接口
 * @author
 */
@RestController
@RequestMapping("file")
@Api(tags = "文件通用上傳下載")
public class FileController {

    @Autowired
    private FilePathProperties filePathProperties;

    /**
     * 上傳文件
     *
     * @param file
     * @return
     */
    @PreAuthorize(hasPermi = "system:file:upload")
    @PostMapping("upload")
    @ApiOperation("上傳")
    public AjaxResult uploadFile(@Param("file") MultipartFile file) {
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            // 顯示頭像文件夾路徑
            String path = filePathProperties.getPath() + "/" + DateUtils.datePath() + "/";
            FileUtils.check_folder(path);
            // 上傳后的文件名稱
            String auth_file_name = UploadUtil.save_file(file, path);
            if (StringUtils.isEmpty(auth_file_name)){
                return AjaxResult.error(HttpStatus.BAD_REQUEST, "文件格式不合法");
            }
            ajaxResult.put("code", 200);
            ajaxResult.put("message", "成功");
            ajaxResult.put("fileName", path + auth_file_name);
        } catch (IOException e) {
            ajaxResult.put("code", 400);
            ajaxResult.put("message", "上傳失敗");
            e.printStackTrace();
        }
        return ajaxResult;
    }

    /**
     * 下載文件
     * @param fileName
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    @ApiOperation("下載")
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        File file = new File(fileName);
        // 清空response
        response.reset();
        // 設置response的Header 通知瀏覽器 已下載的方式打開文件 防止文本圖片預覽
        response.addHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1")); // 轉碼之后下載的文件不會出現中文亂碼
        response.addHeader("Content-Length", "" + file.length());
        // 以流的形式下載文件
        InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
}

 

然后這里的filePathProperties是讀取配置文件中配置的文件上傳路徑

 

 

然后需要在代碼中添加讀取配置文件的配置類

 

/**
 * 讀取服務器上傳文件磁盤路徑
 */
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "file")
public class FilePathProperties {
    /**
     * 傳文件磁盤路徑
     */
    private String path;

    public String getPath()
    {
        return path;
    }

    public void setPath(String path)
    {
        this.path = path;
    }
}

 

然后前端調用上傳文件接口,並且將照片上傳到服務器上指定的路徑下,再調用保存接口時將通用上傳接口返回的文件路徑作為保存接口的參數

 

 

然后照片就會上傳到服務器上指定的路徑

 

 

然后就是添加靜態資源映射的配置類

package com.ruoyi.fzys.config;

import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.fzys.config.properties.FilePathProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;


/**
 * 通用配置
 *
 * @author ruoyi
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{

    @Autowired
    private FilePathProperties filePathProperties;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** 本地文件上傳路徑 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);

    }

    /**
     * 自定義攔截規則
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {

    }
}

 

這里實現WebMvcConfigurer的addResourceHandlers方法

主要是通過下面實現靜態資源映射

registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);

 

前面是請求資源的路徑,后面是磁盤中的實際路徑。

為了使請求資源的路徑的前綴一致,將其配置得全局常量類中

    /**
     * 資源映射路徑 前綴  自定義
     */
    public static final String RESOURCE_PREFIX_DEFINED = "/file";

 

然后在將圖片路徑保存到數據的接口中

    public AjaxResult add(@RequestBody BusPhotoManagement busPhotoManagement, HttpServletRequest request)
    {
        String filePath = filePathProperties.getPath();
        String path=busPhotoManagement.getPhotoPath().substring(filePath.length());
        //獲取協議號
        String localAddr = request.getLocalAddr();
        int localPort = request.getLocalPort();
        String finalURL= Constants.HTTP +localAddr+":"+localPort+Constants.RESOURCE_PREFIX_DEFINED+path;
        System.out.println("最終路徑 finalURL:"+finalURL);
        busPhotoManagement.setPhotoPath(finalURL);
        return toAjax(busPhotoManagementService.insertBusPhotoManagement(busPhotoManagement));
    }

 

其中filePathProperties和上面使用的配置文件路徑的一樣

busPhotoManagement.getPhotoPath().substring(filePath.length());就是上面調用通用上傳接口返回的實際的磁盤路徑

Constants.HTTP 是全局常量

    /**
     * http請求
     */
    public static final String HTTP = "http://";

 

然后最終將finalURL存儲到數據庫中就是該照片的網絡url

能直接在瀏覽器中訪問

 

 


免責聲明!

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



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