SpringBoot上传文件并配置本地资源映射来访问文件的实例代码

 更新时间:2021年04月23日 10:54:39   作者:weixin_44953227  
这篇文章主要介绍了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上传文件资源映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 从0开始教你开发一个springboot应用

    从0开始教你开发一个springboot应用

    这篇文章主要为大家介绍了从0开始开发一个springboot应用教程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Java后端产生验证码后台验证功能的实现代码

    Java后端产生验证码后台验证功能的实现代码

    这篇文章主要介绍了Java后台产生验证码后台验证功能,本文文字结合实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • 使用spring框架ResponseEntity实现文件下载

    使用spring框架ResponseEntity实现文件下载

    这篇文章主要介绍了使用spring框架ResponseEntity实现文件下载,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • 解决ObjectMapper.convertValue() 遇到的一些问题

    解决ObjectMapper.convertValue() 遇到的一些问题

    这篇文章主要介绍了解决ObjectMapper.convertValue() 遇到的一些问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Java多例Bean的应用场景-easyExcel导入

    Java多例Bean的应用场景-easyExcel导入

    EasyExcel 是一个基于 Java 的简单、省内存的读写 Excel 的开源项目。这篇文章主要介绍了用easyExcel导入Java Bean的应用场景,感兴趣的朋友可以参考阅读
    2023-04-04
  • Java数据结构之散列表(动力节点Java学院整理)

    Java数据结构之散列表(动力节点Java学院整理)

    散列表(Hash table,也叫哈希表),是根据关键字(key value)而直接进行访问的数据结构。这篇文章给大家介绍了java数据结构之散列表,包括基本概念和散列函数相关知识,需要的的朋友参考下吧
    2017-04-04
  • 图解Java经典算法插入排序的原理与实现

    图解Java经典算法插入排序的原理与实现

    插入排序的算法描述是一种简单直观的排序算法。其原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。本文将用Java语言实现插入排序算法并进行可视化,感兴趣的可以了解一下
    2022-09-09
  • Java中一些关键字的使用技巧总结

    Java中一些关键字的使用技巧总结

    这篇文章主要介绍了Java中一些关键字的使用技巧总结,其中重点讲述了this和super两个关键字的用法,需要的朋友可以参考下
    2015-09-09
  • Spring循环依赖的解决方法详解

    Spring循环依赖的解决方法详解

    Spring的解决循环依赖是有前置条件的,要解决循环依赖我们首先要了解Spring Bean对象的创建过程和依赖注入的方式。依赖注入方式,我之前的博客有所分享,大家可以在看本篇文章之前进行一下小小的回顾
    2022-08-08
  • 教你怎么使用hadoop来提取文件中的指定内容

    教你怎么使用hadoop来提取文件中的指定内容

    发现有很多小伙伴不会使用hadoop来提取文件中的指定内容,今天特地整理了这篇文章,文中有非常详细的代码示例,对不会这个方法的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05

最新评论