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

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;
			  }
			});
		},
		
	})
}
相关推荐
sinat_2622921116 分钟前
Java面试实战:音视频场景下的微服务架构与缓存技术剖析
java·spring boot·redis·微服务·kafka·分布式系统·面试技巧
mask哥20 分钟前
详解springcloudalibaba采用prometheus+grafana实现服务监控
java·nacos·springboot·grafana·prometheus·springcloud·微服务监控
振鹏Dong22 分钟前
Java基础&集合 面试经典八股总结 [连载ing]
java
不当菜虚困4 小时前
JAVA设计模式——(二)组合模式
java·设计模式·组合模式
jack_xu5 小时前
经典大厂面试题——缓存穿透、缓存击穿、缓存雪崩
java·redis·后端
CHQIUU6 小时前
Java 设计模式心法之第4篇 - 单例 (Singleton) 的正确打开方式与避坑指南
java·单例模式·设计模式
碎梦归途7 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
lozhyf7 小时前
Eureka搭建
java·spring cloud
幽络源小助理7 小时前
SpringBoot民宿管理系统开发实现
java·spring boot·springboot·民宿系统
东阳马生架构7 小时前
Nacos简介—1.Nacos使用简介
java