FastAPI+JS实现图片下载:前端接收响应报错求助
解决FastAPI+JS图片下载报错问题
先排查后端接口问题
你的报错里出现<!DOCTYPE,大概率是后端路由没匹配上,返回了404的HTML页面,而非图片数据。先确保FastAPI接口能正确返回图片:
后端FastAPI代码示例
from fastapi import FastAPI from fastapi.responses import FileResponse import os app = FastAPI() # 定义download目录的绝对路径 DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "download") @app.get("/download-image/{filename}") async def download_image(filename: str): file_path = os.path.join(DOWNLOAD_DIR, filename) # 检查文件是否存在 if not os.path.exists(file_path): return {"error": "文件不存在"} # 返回图片,可手动指定媒体类型,比如image/jpeg、image/png return FileResponse(file_path, media_type="image/jpeg", filename=filename)
前端JavaScript处理方式
不能用response.json()处理图片,因为图片是二进制Blob数据,以下两种可行方案:
方案1:直接用a标签跳转(最简单)
给按钮绑定点击事件,创建临时a标签触发下载:
<button onclick="downloadImage()">下载图片</button> <script> function downloadImage() { const filename = "test.jpg"; // 替换为目标图片文件名 const a = document.createElement("a"); a.href = `/download-image/${filename}`; // 对应后端路由 a.download = filename; // 指定下载后的文件名 document.body.appendChild(a); a.click(); document.body.removeChild(a); } </script>
方案2:用Fetch获取Blob再创建下载链接
如果需要先执行前置逻辑再下载,用这种方式:
<button onclick="downloadImage()">下载图片</button> <script> async function downloadImage() { try { const filename = "test.jpg"; const response = await fetch(`/download-image/${filename}`); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } // 将响应转为Blob格式 const blob = await response.blob(); // 创建临时下载链接 const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); // 释放临时URL资源 URL.revokeObjectURL(url); document.body.removeChild(a); } catch (error) { console.error("下载失败:", error); } } </script>
注意事项
- 确保后端的
download目录存在且包含目标图片文件 - 后端路由要和前端请求的路径完全匹配,避免因404返回HTML页面
- 如果是跨域场景,需要在FastAPI中配置CORS中间件(使用
fastapi.middleware.cors.CORSMiddleware)
内容的提问来源于stack exchange,提问作者user21321051
相关产品推荐
相关产品推荐

