FastAPI后端图片无法在前端显示,提示文件不存在求助
解决FastAPI图片显示与文件不存在错误问题
问题描述
已基于FastAPI实现两个接口:
/uploadlink/:接收链接参数,通过网页抓取下载图片到本地/image_folder/image.png/:返回已下载的图片
当前问题:
- 调用图片接口时出现500内部服务器错误,提示
RuntimeError: File at path /image_folder/image.png does not exist - 前端无法正常显示后端下载的图片
核心错误分析
代码中使用os.chdir('image_folder')切换工作目录,导致后续FileResponse("/image_folder/image.png")查找的是系统根目录下的路径,而非项目目录下的image_folder;同时多次调用接口会持续切换工作目录,引发路径混乱。
修复方案
1. 后端代码修正(main.py)
修正/uploadlink/接口路径逻辑
移除os.chdir,直接构造相对项目根目录的完整文件路径,避免工作目录混乱:
@app.post('/uploadlink/') async def get_basic_form(request: Request, link: str = Form(...)): logging.info("Method has been called") image_dir = 'image_folder' if not os.path.exists(image_dir): os.makedirs(image_dir) # 构造完整的图片保存路径,避免工作目录切换导致的路径错误 image_path = os.path.join(image_dir, 'image.png') url = link # 补充合法User-Agent,避免被目标网站拦截请求 HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'}) webpage = requests.get(url, headers=HEADERS) soup = BeautifulSoup(webpage.content, "html.parser") images = soup.find_all("img", class_='hCL kVc L4E MIw') images_list = [] real_image = "" for img in images: if img.has_attr('src'): images_list.append(img['src']) # 优化查找逻辑,找到目标图片后立即停止循环 for img_url in images_list: if '736x' in img_url: real_image = img_url break if real_image: # 请求图片时同样携带User-Agent r = requests.get(real_image, headers=HEADERS) with open(image_path, 'wb') as f: f.write(r.content) return {"link": link}
修正图片返回接口
修改接口路径,先检查文件是否存在,避免返回500错误:
@app.get("/image/") async def get_image(): image_path = os.path.join('image_folder', 'image.png') # 先校验文件是否存在,返回404而非500 if not os.path.exists(image_path): return {"error": "Image not found"}, 404 return FileResponse(image_path)
2. 前端代码优化(index.html)
无需额外AJAX请求图片接口,直接将img标签的src指向图片接口,同时添加时间戳避免浏览器缓存旧图片:
<script> $(document).ready(function(){ $('#upload-form').on('submit', function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ type: 'POST', url: '/uploadlink/', data: formData, processData: false, contentType: false, success: function(response){ console.log(response); // 直接设置图片src为后端接口,添加时间戳避免缓存 $('#generated-image').attr('src', '/image/?t=' + new Date().getTime()); $('#generated-image').show(); }, error: function(xhr){ console.error('图片抓取失败:', xhr.responseText); } }); }); }); </script>
额外优化建议
- 避免文件覆盖:不要固定使用
image.png作为文件名,可通过UUID或时间戳生成唯一文件名,防止多用户同时使用时互相覆盖 - 增强异常处理:添加网页请求失败、图片标签未找到等场景的异常捕获,返回明确的错误信息
- 使用绝对路径:可通过
os.path.abspath(image_dir)获取项目目录的绝对路径,进一步避免路径问题
内容的提问来源于stack exchange,提问作者Karthik Gajendiran
相关产品推荐
相关产品推荐

