Java Spring后端向React前端传递PNG图片无法渲染问题求助
React前端无法渲染Spring后端返回的PNG图片问题解决
问题背景
已从Java Spring后端成功获取PNG图片二进制数据,但React的<img>标签无法正常渲染图片。
后端代码(Spring Boot)
@PostMapping("/getProduct/{type}") @ResponseBody public ResponseEntity<byte[]> getProduct(@PathVariable("type") String productName) { String filePath = DIRECTORY_UPLOAD + PRODUCTS + File.separator; List<File> files = findAllFile(filePath); File productFile = files.stream() .filter(f -> f.getName().contains(productName)) .findFirst() .orElse(null); if (productFile != null && productFile.exists()) { try { byte[] imageBytes = Files.readAllBytes(productFile.toPath()); return ResponseEntity.ok() .contentType(MediaType.IMAGE_PNG) .body(imageBytes); } catch (IOException e) { e.printStackTrace(); // 需优化异常处理 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } }
前端代码(React + Axios)
接口请求方法
getImage(type: string): Promise<Response> { return axios.post("api" + PATH_UPLOAD + "/getProduct/" + type.replace("/",""), { headers: { ...authHeader(), "Content-Type": "multipart/form-data", }, }); }
图片获取与渲染逻辑
useEffect(() => { const fetchImage = async () => { await ProductsService.getImage(data.type).then(res => { if (res.status === 200) { const file = new Blob([res.data], { type: "image/png", }); let fileurl = URL.createObjectURL(file); console.log(fileurl); setProductImgURL(fileurl); } }) }; fetchImage(); }, []);
图片渲染标签
{ productImgURL === "" ? "" : <img src={productImgURL} alt="Image Produit" className="image" style={{width: "25%", height: "25%"}}/> }
已完成的排查操作
- 验证后端接口功能正常,网络请求返回200状态码且响应包含图片数据
- 尝试多种Blob创建方式,打印
res.data内容确认数据存在
解决方案
1. 修正Axios响应类型配置
Axios默认会将响应解析为JSON格式,这会破坏二进制图片数据。需显式设置responseType: 'arraybuffer':
getImage(type: string): Promise<Response> { return axios.post("api" + PATH_UPLOAD + "/getProduct/" + type.replace("/",""), {}, { headers: { ...authHeader() }, responseType: 'arraybuffer' // 关键配置:确保获取原始二进制数据 }); }
2. 移除不必要的Content-Type设置
当前请求无需上传表单数据,因此删除"Content-Type": "multipart/form-data"配置,避免请求头与实际数据格式不匹配。
3. 优化useEffect依赖(可选)
若data.type可能动态变化,需将其添加到useEffect的依赖数组中,确保类型变更时重新请求图片:
useEffect(() => { // ... 原有逻辑 }, [data.type]);
4. 清理Blob URL(可选)
为避免内存泄漏,组件卸载时应释放创建的Blob URL:
useEffect(() => { const fetchImage = async () => { // ... 原有逻辑 }; fetchImage(); return () => { if (productImgURL) { URL.revokeObjectURL(productImgURL); } }; }, [data.type]);
内容的提问来源于stack exchange,提问作者Ultiorra
相关产品推荐
相关产品推荐

