如何通过localhost访问Python WebAPI项目receivedfiles目录下的文件
问题:如何通过Web服务访问上传至receivedfiles目录的文件?
问题背景
我在MacOS Ventura系统上运行端口为5000的Python Flask WebAPI,在myapp.py所在目录创建了receivedfiles文件夹,文件上传功能正常,可通过localhost:5000或192.168.1.2上传文件到该目录。但通过浏览器或Flutter应用访问192.168.1.2:5000/receivedfiles/sampleimage1.png时返回“not found”,本地可通过file:///Users/myusername/myprojects/mypyhtonprojects/webapiproject1/receivedfiles/sampleimage1.png访问该文件。
上传代码:
@app.route('/api/uploadfile', methods=['GET','POST']) def uploadafile(): if 'myfile' not in request.files: return 'file could not be uploaded.', 400 myfile = request.files['myfile'] if myfile.filename == '': return 'please specify the filename', 400 # save the file to the receivedfiles folder myfile.save('receivedfiles/' + myfile.filename) return 'successfully uploaded', 200
目录结构:
├── myapp.py # WebAPI运行文件 └── receivedfiles/ # 上传文件存储目录 └── sampleimage1.png # 已上传的示例文件
解决方案
Flask默认仅暴露static和templates目录给Web访问,需手动配置才能让receivedfiles目录的文件可通过Web路径访问,以下是两种可行方法:
方法1:创建自定义路由返回文件
在myapp.py中添加如下代码,通过send_from_directory安全返回指定目录的文件:
from flask import send_from_directory import os # 获取当前脚本所在目录的绝对路径 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 拼接receivedfiles目录的绝对路径 RECEIVED_FILES_DIR = os.path.join(BASE_DIR, 'receivedfiles') @app.route('/receivedfiles/<path:filename>') def serve_uploaded_file(filename): # 从指定目录返回文件,自动处理MIME类型 return send_from_directory(RECEIVED_FILES_DIR, filename)
- 此路由会匹配所有
/receivedfiles/xxx格式的请求,返回对应文件 - 使用绝对路径拼接可避免路径遍历风险,适配不同系统的路径格式
方法2:将receivedfiles设为静态目录
初始化Flask应用时,直接将receivedfiles配置为静态目录,让Flask自动处理文件请求:
from flask import Flask import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) app = Flask( __name__, static_folder='receivedfiles', static_url_path='/receivedfiles' )
- 此方式无需额外编写路由,
/receivedfiles/路径下的所有文件可直接访问 - 若需保留原
static目录的功能,建议使用方法1,或通过扩展实现多静态目录
额外优化建议
- 上传代码存在路径遍历风险,建议将
myfile.save('receivedfiles/' + myfile.filename)改为:myfile.save(os.path.join('receivedfiles', myfile.filename)) - 重启Flask应用后配置才会生效
- 确保
receivedfiles目录的MacOS权限设置正确,Web进程需具备读取权限
内容的提问来源于stack exchange,提问作者Emsil Neumann
相关产品推荐
相关产品推荐

