微信小程序显示流格式照片

1.服务端,java代码,用于将图片转为文件流返回给前端

java 复制代码
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Demo {

    @GetMapping("/aaaaaa")
    public ResponseEntity<Resource> getImage(String imageName) throws Exception {
        // 构建图片的路径
        Path imagePath = Paths.get("D:\\1.png");
        
        // 检查文件是否存在
        if (!Files.exists(imagePath)) {
            throw new Exception("Image not found");
        }
        
        // 将图片文件转换为Resource对象,以便Spring管理
        Resource resource = new UrlResource(imagePath.toUri());
        
        // 设置响应头,指定内容类型和文件名(对于下载特别有用)
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + imageName);
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE); // 根据实际情况调整MIME类型
        
        // 返回文件流和响应头
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}

2.微信小程序端,请求文件流,并将图片转码

javascript 复制代码
getImage(){
	const that = this
	uni.request({
		url:"http://127.0.0.1/aaaaaa",
		method: 'GET',
		dataType:'json',
		responseType: 'arraybuffer', // 指定返回类型为二进制数据流
		data: {},
		success:(res)=>{
			// 将返回的文件流数据写入临时文件
			const fsm = wx.getFileSystemManager();
			const filePath = wx.env.USER_DATA_PATH + '/temp-image.jpg';
			fsm.writeFile({
			  filePath: filePath,
			  data: res.data,
			  encoding: 'binary',
			  success() {
				// 将临时文件路径绑定到页面上的image组件
				that.imgSrc=filePath;
			  }
			});
		},
		
	})
}
相关推荐
可观测性用观测云7 小时前
Pyroscope Java 接入最佳实践
java
气π8 小时前
【JavaWeb】——(若依 + AI)-基础学习笔记
java·spring boot·笔记·学习·java-ee·mybatis·ruoyi
阿里云云原生8 小时前
AgentScope Java 1.0:从模型到应用,AI Agent 全生命周期管理利器!
java·云原生
running up8 小时前
Maven依赖管理和项目构建工具
java·maven
老华带你飞9 小时前
列车售票|基于springboot 列车售票系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
java_logo9 小时前
LinuxServer.io LibreOffice 容器化部署指南
java·开发语言·docker·dubbo·openoffice·libreoffice·opensource
qq_589568109 小时前
@NotBlank与@NotEmpty注解无法导入
java·开发语言
李拾叁的摸鱼日常9 小时前
Spring Boot中OncePerRequestFilter原理与Filter单次调用控制全解析
java·后端
script.boy9 小时前
基于spring boot校园二手交易平台的设计与实现
java·spring boot·后端
爱潜水的小L10 小时前
自学嵌入式day30,回收进程
java·linux·服务器