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


    说两种方式,直接上代码:
    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
  • 相关阅读:
    基于System-Verilog的VGA彩条设计与仿真
    Jetpack:005-文本组件的扩展
    RK3568 + 国产 PHY YT8531 调试
    python的re正则表达式
    分享一款Linux环境下常用的debug工具--GDB调试工具
    AMBA总线相关知识记录
    已经刷新了四大公开数据集纪录?吃一记新ReID数据集安利!
    jenkins工具系列 —— 插件 使用Changelog获取commit记录
    访谈-John Carmack-2022
    python解决循环依赖
  • 原文地址:https://blog.csdn.net/weixin_46064585/article/details/136280707