Springboot文件上传机制[通俗易懂]

Springboot文件上传机制[通俗易懂]springboot文件上传机制:1.访问路径2. 上传完成后返回访问文件地址3. 我们只需要访问返回的地址就可以访问到图片4. yaml配置文件(localpath是实际存储的地址)5. 添加配置类,进行访问地址和存储地址映射 @Value(“${file.upload.suffixPath}”) private String uploadSuffixPath; @Value(“${file.upload.localPath}”) private Strin

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

springboot文件上传机制:

注意,存储到数据库中的只是路径名
1.访问路径在这里插入图片描述
2. 上传完成后返回访问文件地址
在这里插入图片描述
3. 我们只需要访问返回的地址就可以访问到图片
在这里插入图片描述
4. yaml配置文件(localpath是实际存储的地址)
在这里插入图片描述
5. 添加配置类,进行访问地址和存储地址映射

    @Value("${file.upload.suffixPath}")
    private String uploadSuffixPath;
    @Value("${file.upload.localPath}")
    private String uploadLocalPath;
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){ 
   
        AppFileUtils.uploadSuffixPath = uploadSuffixPath;
        AppFileUtils.uploadLocalPath = uploadLocalPath;
        registry.addResourceHandler(uploadSuffixPath+"/**").addResourceLocations("file:"+uploadLocalPath);
    }
  1. 实际上传文件代码
package com.yglh.utils;

import org.aspectj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Component
public class AppFileUtils { 
   

    private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /** * 文件上传路径前缀 */
    public static String uploadSuffixPath;
    /** * 本地磁盘目录 */
    public static String uploadLocalPath;

    /** * date format yyyyMMdd */
    public static final String PATTERN_yyyyMMdd = "yyyyMMdd";
    /** * date format yyyyMMddHHmmssSSS */
    public static final String PATTERN_yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS";


    /** * @Description: 单文件上传到本地磁盘 * @param multipartFile * @return: java.lang.String * @Author: lxt * @Date: 2021/3/29 10:30 */
    public static String uploadFile(MultipartFile multipartFile){ 
   
        if(multipartFile == null){ 
   
            return null;
        }
        //产生文件名称
        String fileName = getUploadFileName(multipartFile.getOriginalFilename());
        //产生文件目录
        String dateDir = format(null,PATTERN_yyyyMMdd);
        File destFileDir = new File(uploadLocalPath + File.separator + dateDir);
        //因为目录每天凌晨更新所以要判断是否存在,如果不存在就创建新的文件
        if(!destFileDir.exists()){ 
   
            destFileDir.mkdirs();
        }
        try { 
   
        	//把上传文件到目的目录中去
            File destFile = new File(destFileDir.getAbsoluteFile()+File.separator+fileName);
            multipartFile.transferTo(destFile);
            logger.info("文件【"+multipartFile.getOriginalFilename()+"】上传成功");
            return uploadSuffixPath + "/" + dateDir+"/"+fileName;
        } catch (IOException e) { 
   
            logger.error("文件上传异常:"+multipartFile.getOriginalFilename(),e);
            return null;
        }
    }


    /** * @Description: 获取上传后的文件相对路径 --数据库存储该路径 * @param fileName * @return: java.lang.String * @Author: lxt * @Date: 2021/3/29 10:30 */
    public static String getUploadFileName(String fileName){ 
   
        return new StringBuilder()
                .append(format(null, PATTERN_yyyyMMddHHmmssSSS))
                .append("_").append(getRandomStrByNum(6))
                .append(getExtension(fileName))
                .toString();
    }

    /** * 格式化时间 * @param localDateTime * @param pattern 格式 * @return */
    public static String format(LocalDateTime localDateTime, String pattern){ 
   
        //默认取当前时间
        localDateTime = localDateTime == null ? LocalDateTime.now() : localDateTime;
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String CHAR_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /** * @Title: getRandomStrByNum * @Description: 获取不同位数的随机字符串 * @Author: lxt * @param: factor * @return: java.lang.String * @throws: */
    public static String getRandomStrByNum(int factor) { 
   
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < factor; i++) { 
   
            sb.append(CHAR_STR.charAt(random.nextInt(36)));
        }
        return sb.toString();
    }
    /** * @Description: 获取扩展名 * @param fileName * @return: java.lang.String * @Author: lxt */
    public static String getExtension(String fileName){ 
   
        return fileName.substring(fileName.lastIndexOf("."));
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/168998.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • stm32新手入门什么是寄存器_STM32H7寄存器

    stm32新手入门什么是寄存器_STM32H7寄存器小白单片机入门必看,俗话说得好基础不牢地动山摇,要学好单片机一定要熟知底层原理

    2022年9月6日
    2
  • 命令模式 Command「建议收藏」

    命令模式 Command「建议收藏」命令模式 Command动机模式定义实例结构要点总结笔记动机在软件构建过程中,“行为请求者”与”行为实现者”通常呈现一种”紧耦合”,但在某些场合—-比如需要对行为进行记录,撤销/重(Undo / Redo),事务”等处理,这种无法抵御变化的紧耦合是不合适的在这种情况下,如何将”行为请求者”和”行为实现这”解耦?将一组行为抽象为对象,可以实现两者之间的松耦合模式定义将一个请求(行为)封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作实例#i

    2022年8月8日
    4
  • ELF文件格式简介「建议收藏」

    ELF文件格式简介「建议收藏」  简单了解下ELF文件的格式。1简介  可执行与可链接格式(ExecutableandLinkableFormat,ELF),常被称为ELF格式,是一种用于可执行文件、目标代码、共享库和核心转储(coredump)的标准文件格式,一般用于类Unix系统,比如Linux,Macox等。ELF格式灵活性高、可扩展,并且跨平台。比如它支持不同的字节序和地址范围,所以它不会不兼容某一特别的CPU或指令架构。这也使得ELF格式能够被运行于众多不同平台的各种操作系统所广泛采纳。  E.

    2022年10月25日
    0
  • 论文讨论&&思考《Deformable Convolutional Networks》

    论文讨论&&思考《Deformable Convolutional Networks》这篇论文真是让我又爱又恨,可以说是我看过的最认真也是最多次的几篇paper之一了,首先deformableconv的思想我觉得非常好,通过end-to-end的思想来做这件事也是极其的makese

    2022年8月6日
    3
  • 虚函数指针sizeof不为sizeof(void*)

    虚函数指针sizeof不为sizeof(void*)

    2021年9月1日
    73

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号