SpringBoot上傳文件並配置本地資源映射來訪問文件的實例代碼

1.準備工作

1、新建一個SpringBoot項目加上web依賴, 所有依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
</dependency>

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

2、application.properties

# 上傳文件總的最大值
spring.servlet.multipart.max-request-size=10MB
#spring.servlet.multipart.max-request-size=10KB
# 單個文件的最大值
spring.servlet.multipart.max-file-size=10MB
#spring.servlet.multipart.max-file-size=10KB

# 文件上傳路徑, 當前項目根目錄下的 uploadFile 目錄
pro.uploadPath=uploadFile

3、新建文件上傳的靜態文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上傳</title>
</head>
    <body>
        <h1>文件上傳</h1>
        <form method="post" action="/file/upload" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>
    </body>
</html>

2. 配置本地資源映射路徑 addResourceHandlers

package com.pro.conf;

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 WebMvcConf implements WebMvcConfigurer {
    @Value("${pro.uploadPath}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(uploadPath + "/**") // 添加訪問路徑
                // file: 當前項目根目錄, 映射到真實的路徑下的 uploadPath(變量)目錄下
                .addResourceLocations("file:" + uploadPath + "/");
    }
}

3.上傳代碼

package com.pro.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UploadController {
    @Value("${pro.uploadPath}")
    private String uploadPath;

    /**
     * 獲取文件路徑
     * @param request 請求體
     * @param fileName 文件名稱
     * @return 文件路徑
     */
    public String getUploadPath(HttpServletRequest request, String fileName) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + uploadPath + "/" + fileName;
    }

    // 文件上傳, 上傳到當前項目根目錄下的 uploadFile 目錄
    @RequestMapping("/file/upload")
    public Object upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        map.put("msg", "上傳成功");

        if (multipartFile.isEmpty()) {
            map.put("msg", "空文件");
            return map;
        }

        // 獲取文件名
        String fileName = multipartFile.getOriginalFilename();
        if ("".equals(fileName)) {
            map.put("msg", "文件名不能為空");
            return map;
        }
        System.out.println("上傳文件原始的名字: " + fileName);

        // 使用uuid生成新文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("保存的文件的新名字: " + newFileName);

        // 獲取年月日的日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());

        // 生成以日期分割的文件路徑
        File readPath = new File(uploadPath + File.separator + format);
        System.out.println("存放的文件夾: " + readPath);
        System.out.println("存放文件的絕對路徑: " + readPath.getAbsolutePath());
        // 判斷文件夾是否存在
        if (!readPath.isDirectory()) {
            // 創建文件夾
            readPath.mkdirs();
        }

        // 文件真實的保存路徑
        File file = new File(readPath.getAbsolutePath() + File.separator + newFileName);
        try {
            multipartFile.transferTo(file);

            // 獲取存儲路徑
            String filePath = getUploadPath(request, format + "/" + newFileName);
            map.put("path", filePath);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg", "上傳失敗");
        }

        return map;
    }
}

到此這篇關於SpringBoot上傳文件並配置本地資源映射來訪問文件的文章就介紹到這瞭,更多相關SpringBoot上傳文件資源映射內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!