• 上传到服务器的图片资源如何读取


    说两种方式,直接上代码:
    1.前提图片已经存储在服务器上,携带图片地址过去通过输入输出流进行图片下载查看
    前端:

    <img v-else :src="'/chat/download?name='+message.url"/>
    
    • 1

    后端:

    @GetMapping("/download")
        public void download(String name, HttpServletResponse response) {
    
            try {
                //输入流,通过输入流读取文件内容
                FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
    
                //输出流,通过输出流将文件写回浏览器
                ServletOutputStream outputStream = response.getOutputStream();
    
                response.setContentType("image/jpeg");
    
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                    outputStream.flush();
                }
    
                //关闭资源
                outputStream.close();
                fileInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    2.通过1的方式不能直接获取http/https路径进行访问,接下来看第二种方式
    2.1—先写静态资源映射

    @Configuration
    @Slf4j
    //public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    public class WebMvcConfiguration implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            log.info("开启静态资源映射");
            // 静态资源映射
           // 这个/www/server/img2 这个是我服务器上存储图片的路径
            registry.addResourceHandler("/img2/**").addResourceLocations("file:/www/server/img2/");  
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    这样映射后就能通过http/https进行访问,可以:src进行动态绑定,然后拼装路径就可以直接访问

    
    
    • 1
  • 相关阅读:
    3个变化3秒区别MT4和MT5
    采购策略中的合同支付类型
    2022软件测试高频面试题汇总(附带答案)——建议收藏
    nexus搭建测试docker&maven&npm仓库
    [springboot源码分析]-Conditional
    接口自动化中cookies的处理技术
    国产数据库四十年磨一剑,达梦数据科创板上市
    25-数据结构-稀疏矩阵-三元组
    2023年阿里云双11优惠活动,省钱攻略来了!
    Spring Boot 事务详解
  • 原文地址:https://blog.csdn.net/weixin_46064585/article/details/136280707