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

相关推荐
伤不起bb8 分钟前
MySQL 高可用
linux·运维·数据库·mysql·安全·高可用
拾贰_C9 分钟前
【SpringBoot】MyBatisPlus(MP | 分页查询操作
java·spring boot·后端·spring·maven·apache·intellij-idea
猛踹瘸子那条好腿の13 分钟前
Spring-boot初次使用
java·springboot
我不是程序猿儿2 小时前
【C#】 lock 关键字
java·开发语言·c#
tmacfrank3 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
weixin_472339464 小时前
Maven 下载安装与配置教程
java·maven
Magnum Lehar5 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Yushan Bai5 小时前
ORACLE RAC环境REDO日志量突然增加的分析
数据库·oracle
躺着听Jay5 小时前
Oracle-相关笔记
数据库·笔记·oracle
就叫飞六吧5 小时前
Spring Security 集成指南:避免 CORS 跨域问题
java·后端·spring