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

相关推荐
学c真好玩1 分钟前
Spring
java·后端·spring
沉默王二4 分钟前
更快更强!字节满血版DeepSeek在IDEA中真的爽!
java·前端·程序员
2301_807449205 分钟前
字符串相乘——力扣
java·算法·leetcode
小五Z10 分钟前
RabbitMQ高级特性--消息确认机制
java·rabbitmq·intellij-idea
Kevinyu_21 分钟前
Maven
java·maven
nickxhuang26 分钟前
【基础知识】回头看Maven基础
java·maven
程序员总部28 分钟前
如何应对Maven中的依赖导入挑战?
数据库·sql·maven
日月星辰Ace1 小时前
jwk-set-uri
java·后端
xiao--xin1 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
钢板兽1 小时前
Java后端高频面经——Spring、SpringBoot、MyBatis
java·开发语言·spring boot·spring·面试·mybatis