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

发布于 2021-06-15  4624 次阅读


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

繁华落尽,雪花漫天飞舞。