在win10本地开发springboot项目能上传图片,并能通过URL直接从浏览器访问,但是部署到服务器上后能上传文件,但是通过浏览器无法访问图片

本文档介绍了一个SpringBoot项目在Windows和Linux环境下处理图片上传与访问的问题。项目在本地可以正常上传图片并从浏览器访问,但在服务器上只能上传而无法访问。解决方案包括根据操作系统设置不同的文件路径,并通过WebMvcConfigurer配置静态资源处理,确保图片能够被正确访问。同时,文章还提供了详细的代码实现和配置步骤。
摘要由CSDN通过智能技术生成

在win10本地开发springboot项目能上传图片,并能通过URL直接从浏览器访问,但是部署到服务器上后能上传文件,但是通过浏览器无法访问图片

1.首先springboot项目在Window和Linux服务器的项目资源路径是不一样的,需要分开来设置路径:

 @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public String uploadImage(MultipartFile image, Comment comment, String rootUrl) throws Exception {
        if (comment == null) {
            return null;
        }

        String imgRequestUrl = null;
        if (!image.isEmpty()){
            File imagePath;  //图片存放地址
            //获取文件名称
            String  imageName = image.getOriginalFilename();
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {  //windows系统
                String path = System.getProperty("user.dir");  //获取项目相对路径
                imagePath = new File(path+file_path);
            } else {//linux系统
                //获取根目录
                //如果是在本地windows环境下,目录为项目的target\classes下
                //如果是linux环境下,目录为jar包同级目录
                File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
                if (!rootPath.exists()) {
                    rootPath = new File("");
                }
                imagePath = new File(rootPath.getAbsolutePath()+file_path);
            }
            if (!imagePath.exists()) {
                //不存在,创建
                imagePath.mkdirs();
            }
            //使用工具类生成一个随机的文件名防止文件名重复
            String newImageName = IDUtils.getFilename(imageName);
            //创建图片存放地址
            File imageResultFile = new File(imagePath + "/" + newImageName);
           imgRequestUrl = rootUrl + "/images/" + newImageName;
            if (imageResultFile.exists()) {
                log.info("图片已经存在!该图片的访问请求地址:[{}]", imgRequestUrl);
            } else {
                //图片尚未存在,将图片保存到指定的路径中
                image.transferTo(imageResultFile);
            }
            //将该图片的地址设置到comment中
            comment.setCommentImagePath(imgRequestUrl);
            //图片在磁盘中的实际地址
//        String imageResultPath = imageResultFile.getCanonicalPath();
            log.info("该图片的访问请求地址:[{}]", imgRequestUrl);
        }
        //设置comment
        comment.setIsDeleted(Comment.DEFAULT_ISDELETED_FALSE);
        comment.setStatus(Comment.DEFAULT_STATUS_TRUE);
        comment.setCollection_count(Long.valueOf(0L));
        comment.setLike_count(Long.valueOf(0L));
        int fla = commentMapper.insert(comment);
        if (fla == 1){
            //插入成功返回图片的地址
            return imgRequestUrl;
        }else{
            //插入失败返回NULL
            return  null;
        }
    }

2.然后配置一个WebMvcConfigurer用于解析静态资源图片,将服务器的静态资源目录通过映射到暴露的访问路径:

@Configuration
public class FileConfig implements WebMvcConfigurer {
    @Value("${images.url-path}")
    private String file_path ;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //在windows环境下的图片存放资源路径
        String winPath = System.getProperty("user.dir")+file_path;
        //在Linux环境下的图片存放资源路径
//        String linuxPath = "/usr/local/my_project/images/";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {  //windows系统
            System.out.println(winPath);
            //第一个方法设置访问路径前缀,第二个方法设置资源路径
            registry.addResourceHandler("/images/**").
                    addResourceLocations("file:"+winPath);
        }else{//linux系统
            File rootPath = null;
            try {
                rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if(!rootPath.exists()){
                rootPath = new File("");
            }
            System.out.println(rootPath.getAbsolutePath()+file_path);

           File  imagePath = new File(rootPath.getAbsolutePath()+file_path);
            if(!imagePath.exists()){
                //不存在,创建
                imagePath.mkdirs();
            }
            registry.addResourceHandler("/images/**").
                    addResourceLocations("file:"+rootPath.getAbsolutePath()+file_path);
        }
    }
}

  • addResoureHandler:指的是对外暴露的访问路径
  • addResourceLocations:指的是内部文件放置的目录

image-20210221104716273

image-20210221104630602

3.本博文已同步到个人博客,如有需要请移步:

http://moyisuiying.com/index.php/javastudy/springboot/476.html

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌意随影

您的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值