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

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;
			  }
			});
		},
		
	})
}
相关推荐
程序员清风几秒前
快手二面:Redisson公平锁用用过吗?他的实现原理是什么样子的?
java·后端·面试
皮皮冰燃几秒前
微信小程序-1-微信开发者工具环境搭建和初始化创建项目
微信小程序·小程序
SimonKing几秒前
Java序列化陷阱揭秘:这5个错误80%的开发者都犯过
java·后端·程序员
Seven971 分钟前
Redis容量评估模型
java·redis
jingling5554 分钟前
uniapp | 实现微信小程序端的分包处理
微信小程序·小程序·uni-app
最美不过下雨天啊5 分钟前
微信小程序发送订阅消息-一次订阅,一直发送消息。
微信小程序·php·一次性订阅·长期订阅
€81115 分钟前
Java入门级教程16——JUC的安全并发包机制
java·开发语言·juc的安全并发包机制·栅栏机制·闭锁机制·信号量机制·无锁机制
杨杨杨大侠17 分钟前
Atlas Mapper 教程系列 (2/10):环境搭建与项目初始化
java·开源·github
杨杨杨大侠25 分钟前
Atlas Mapper 教程系列 (1/10):框架概述与设计思路
java·开源·github
2501_9159214336 分钟前
iOS App 性能监控与优化实战 如何监控CPU、GPU、内存、帧率、耗电情况并提升用户体验(uni-app iOS开发调试必备指南)
android·ios·小程序·uni-app·iphone·webview·ux