SpringBoot上傳文件以及映射網絡路徑

一、前言:

我這裏的路徑映射是指:將本地文件路徑映射成網絡URL地址,即通過URL可以訪問到本地文件。

之前文件上傳之後,是在tomcat上來配置路徑映射,但最近用的springboot,直接用

nohup java -jar xxxx.jar &

啓動項目。貌似就無法在tomcat上配置了(可能可以通過配置tomcat插件來進行配置,不過我沒試過)。

我使用的環境:jdk1.8,springboot2.1.1

二、springboot上傳文件

springboot上傳文件和springmvc上傳文件一樣的,個人理解上:springboot本質上還是springmvc。

下面代碼裏有【TODO 標記1】下面配置會用到這裏的“files”

文件上傳:

package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class CommonController {

    /**
     * 文件上傳
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "fileUpload")
    public List<String> fileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        if (files == null || files.size() == 0) {
            // TODO 異常處理
        }
        // 文件路徑,注意斜槓方向
        String filePath = "D:/upload/";

        List<String> urls = new ArrayList<>();

        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                // TODO 異常處理
            }
            // 獲取文件名
            String originalFilename = file.getOriginalFilename();
            // 獲取文件後綴名 .XX
            int suffixIndex = originalFilename.lastIndexOf(".");
            String fileSuffix = originalFilename.substring(suffixIndex);
            // 新文件名
            String newFileName = "xxxx" + fileSuffix;
            // 映射路徑 http://localhost/ + 項目名稱 + 配置的映射路徑 +新的文件名。具體的映射路徑需要看自身的配置
            // TODO 標記1
            String fileUrl = "http://localhost/projectName/files/" + newFileName;
            // 生成新文件路徑
            File dest = new File(filePath + newFileName);
            try {
                file.transferTo(dest);
                urls.add(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 返回值
        return urls;
    }
}

三、springboot配置

由於我用的是springboot2.1.1的,所以我這裏是繼承了WebMvcConfigurationSupport這個類。

下面代碼裏有【TODO 標記2】和上面【TODO 標記1】對應。

import com.isoftstone.teamissue.interceptor.AuthInterceptor;
import com.isoftstone.teamissue.utils.IssueConstant;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    /**
     * 資源映射配置
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 靜態資源訪問配置
//        registry.addResourceHandler("/**")
//                .addResourceLocations("classpath:/META-INF/resources/")
//                .addResourceLocations("classpath:/resources/")
//                .addResourceLocations("classpath:/static/")
//                .addResourceLocations("classpath:/public/");

        // TODO 標記2,這裏的配置要和上面的標記1要對應。
        // "/xx/**" 對應 "http://localhost/projectName/xx/"
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:" + "http://localhost/projectName/files/");

        super.addResourceHandlers(registry);
    }
}

比如你上傳了hello.jpg圖片,通過http://localhost/projectName/files/hello.jpg訪問到圖片。

同理,也可以照此部署html,js等文件。

這樣就可以讓靜態文件和自身項目進行分離,這樣部署項目會方便很多

四、實現原理

有待研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章