后端实现图片上传本地,可采用url查看图片

前言

本文将实现在数据库中存储图片url,url可以在浏览器中访问查看。

整体思路为:

  • 上传图片到本地指定地址
  • 为图片分配url保存至数据库
  • 根据分配url,进行物理地址映射到本地指定地址

具体实现

controller层:

上传图片到本地指定地址,为图片分配url保存至数据库

java 复制代码
@PostMapping("/uploadImg")
    @Operation(summary = "上传图片")
    public Result<String> upload(MultipartFile file, HttpServletRequest request) {

        String subPath = "\\upload\\Img\\";
        String basepath = webFileUrl;
        String path = "";
        String vpath = "";
        String fileType = "";
        Map<String, Object> resultPath = WebFileUtils.saveFile(file, basepath + subPath, request);
        path = resultPath.get("path").toString();
        fileType = resultPath.get("fileType").toString();
        vpath = "/statics/upload/" + "Img" + "/" + fileType + "/" + new File(path).getName();

        return R2.ok(vpath,"上传成功");
    }

其中的WebFileUtils类:

java 复制代码
public static Map<String, Object> saveFile(MultipartFile file, String webFileUrl, HttpServletRequest request) {
        System.out.println();
        String realPath, rootPath = webFileUrl;

        if (webFileUrl.equals("")) {
            //设置主路径
            realPath = request.getServletContext().getRealPath("");
            //将路径设置到当前项目同级,并创建upload文件夹
            rootPath = new File(realPath).getParent() + "\\upload\\";
        }
        //组合文件名
        String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\") + 1);
        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(filename);
        //生成新的文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-","") + extension;

        // 区分上传文件是图片还是视频
        String fileType;
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(filename);
        if (contentTypeFor == null){
            fileType = "video";
            rootPath = rootPath + "\\" + fileType +"\\";
        }else{
            fileType = "image";
            rootPath = rootPath + "\\" + fileType +"\\";
        }

        String filePath = rootPath + newFileName;
        File localFile = new File(filePath);

        // 检测是否存在目录,不存在则创建
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String,Object> result = new MapUtils();
        result.put("path", localFile.getAbsolutePath());
        result.put("fileType", fileType );
        //返回文件的绝对路径
        return result;
    }

此处webFileUrl,替换为上传文件本地保存地址。

config:

在此处完成物理地址映射到本地指定地址

java 复制代码
@Configuration
public class UploadConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/api/statics/upload/Img/image/**")
                .addResourceLocations("file:本地保存地址");
    }
}

至此,如果需要实现前端图片预览查看功能,请求数据库中保存的图片url即可。

相关推荐
挺菜的1 分钟前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
A__tao2 分钟前
一键将 SQL 转为 Java 实体类,全面支持 MySQL / PostgreSQL / Oracle!
java·sql·mysql
一只叫煤球的猫13 分钟前
真实事故复盘:Redis分布式锁居然失效了?公司十年老程序员踩的坑
java·redis·后端
猴哥源码15 分钟前
基于Java+SpringBoot的农事管理系统
java·spring boot
面朝大海,春不暖,花不开30 分钟前
Java网络编程:TCP/UDP套接字通信详解
java·网络·tcp/ip
一只fish33 分钟前
MySQL 8.0 OCP 1Z0-908 题目解析(17)
数据库·mysql
花好月圆春祺夏安1 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
慕y2741 小时前
Java学习第十五部分——MyBatis
java·学习·mybatis
A__tao1 小时前
SQL 转 Java 实体类工具
java·数据库·sql
喝可乐的布偶猫1 小时前
Java类变量(静态变量)
java·开发语言·jvm