使用anonfile模块与FastAPI上传文件报错:files.file is not a directory
解决
files.file is not a directory错误 核心修复步骤
错误根源是anonfile模块的upload方法对传入的文件对象处理逻辑——当直接传递files.file(FastAPI的UploadFile对应的类文件对象)时,模块默认将其视为文件路径而非可读取的文件流,因此抛出“不是目录”的错误。
修改app.py中的上传逻辑,为upload方法显式指定文件名参数:
@app.post("/") async def create_upload_files(uploaded_files: list[UploadFile]): # 将AnonFile实例移到循环外,避免重复创建浪费资源 anon = AnonFile() results = [] for file in uploaded_files: # 显式传入filename参数,告知模块这是文件流+对应文件名 upload = anon.upload(file.file, filename=file.filename) link = upload.url.geturl() direct_link = direct_link_anon(link) results.append({"filename": file.filename, "download_link": direct_link}) # 因前端限制单文件上传,返回第一个文件的结果;若支持多文件可返回完整results列表 return {'download': 'Download', 'result': results[0]['download_link'] if results else None}
额外优化建议
- 添加异常捕获:在
direct_link_anon函数中增加异常处理,避免因请求失败或找不到下载链接导致服务崩溃:
def direct_link_anon(link): try: r1 = requests.get(link) r1.raise_for_status() # 捕获HTTP请求错误 soup1 = BeautifulSoup(r1.content, "html.parser") a_href1 = soup1.find("a", {"id": "download-url"}).get("href") return str(a_href1) except (requests.exceptions.RequestException, AttributeError) as e: print(f"获取直链失败: {e}") return None
- 统一前端配置:Dropzone配置中重复设置了
maxFilesize,保留一个合理值即可(单位为MB):
// 删除重复的maxFilesize设置,保留这一行 maxFilesize: 20000,
- 多文件支持(可选):若需要支持多文件上传,修改前端
uploadMultiple: true,同时后端返回完整的results列表给前端批量渲染下载链接。
内容的提问来源于stack exchange,提问作者CYCNO
相关产品推荐
相关产品推荐

