后端实现图片上传本地,可采用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即可。

相关推荐
FantanLee1 分钟前
idea debug 各个步骤含义
java·intellij-idea
Seven 7 Chihiro2 分钟前
学生管理系统升级(登录注册 + 关联学生管理系统)
java·开发语言
techpupil3 分钟前
idea便捷操作
java·ide·intellij-idea
9毫米的幻想9 分钟前
【C++】—— 模版初阶
java·c语言·开发语言·c++·学习
小笨猪-10 分钟前
Spring事务和事务传播机制
java·数据库·spring
weixin_teach007x11 分钟前
springboot+vue+mybatis计算机毕业设计儿童众筹救助系统+PPT+论文+讲解+售后
前端·数据库·vue.js·spring boot·vue·mybatis
xiaobai_cpp21 分钟前
Spring Boot 应用中注册和使用 Filter
java·spring boot·后端
乄bluefox26 分钟前
Springboot中使用Elasticsearch(部署+使用+讲解 最完整)
java·spring boot·后端·elasticsearch
王清欢Randy33 分钟前
Apache Arrow 的列式内存格式
大数据·数据库·apache arrow·列存储引擎·内存格式
原谅我很悲1 小时前
全局异常处理
java