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

前言

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

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

具体实现

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

@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类:

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:
在此处完成物理地址映射到本地指定地址

@Configuration
public class UploadConfig implements WebMvcConfigurer {

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

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

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
后端获取本地图片URL,可以通过以下步骤实: 1. 首先,您需要将本地上传到服务器或者某个公共的存服务,比如云存储服务(如Amazon S3、阿里云OSS等)。 2. 上传图片后,服务器或存储服务会返回一个公开访问的URL,用于获取该图片。这个URL可以通过上传接口的返回结果或者其他方式获取。 3. 在后端,您可以使用后端框架提供的文件操作功能来获取本地图片URL。具体实现方式取决于您使用的后端框架和编程语言。 4. 如果您使用的是Python和Django框架,可以通过以下步骤获取本地图片URL: - 首先,确保您已经在Django的settings.py文件中配置了静态文件的URL和路径。例如: ```python STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ``` - 然后,在您的视图函数中,使用`static`函数来构建本地图片URL。例如: ```python from django.templatetags.static import static def get_image_url(request): image_path = 'path/to/your/image.jpg' image_url = request.build_absolute_uri(static(image_path)) return image_url ``` 注意:`request`参数是视图函数中的请求对象。 - 最后,在前端或其他需要使用图片URL的地方,调用该视图函数获取本地图片URL。例如: ```html <img src="{% url 'get_image_url' %}" alt="Local Image"> ``` 以上是一个简单的示例,您可以根据具体的后端框架和需求进行调整。请确保您已经正确配置了静态文件的URL和路径,并且服务器能够正确访问到您上传的图片

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值