Flask网站FileNotFoundError求助:无法创建指定静态目录
Flask上传图片时出现FileNotFoundError:找不到创建的目录
错误信息
Mar 25 05:21:07 PM FileNotFoundError: [Errno 2] No such file or directory: 'static/hCJUoWT09QpE'
问题分析
你的代码存在两个核心路径问题:
- 目录创建与保存路径不匹配:你通过
os.mkdir('static/'+post_name)在当前工作目录下创建了static/[post_name]目录,但后续配置的app.config["IMAGE_UPLOADS"] = os.path.join('yff','static', post_name)指向了另一个未创建的路径,导致图片保存时找不到目标目录。 - 相对路径依赖运行环境:直接使用相对路径会受Flask运行时的工作目录影响,一旦启动命令的执行目录不是项目根目录,路径就会出现偏差。
解决方案
1. 基于项目根目录构建绝对路径
先获取Flask项目的根目录绝对路径,彻底避免相对路径的不确定性:
import os # 获取当前文件所在的项目根目录(假设你的Flask主文件在项目根目录下) ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
2. 统一目录创建与保存路径
修改目录创建、文件写入和路径配置的代码,确保所有操作指向同一个路径:
# 生成随机目录名后,构建统一的目标目录绝对路径 target_dir = os.path.join(ROOT_DIR, 'static', post_name) # 使用os.makedirs替代os.mkdir,自动创建不存在的父目录,更健壮 os.makedirs(target_dir, exist_ok=True) # 用with语句自动关闭文件,避免资源泄漏 with open(os.path.join(target_dir, 'README.txt'), 'w') as f: f.write('.') # 配置IMAGE_UPLOADS为正确的绝对路径 app.config["IMAGE_UPLOADS"] = target_dir
3. 修正路由代码中的其他细节
- 修正图片空判断逻辑:
request.files本身永远不为空,需要检查具体的文件列表 - 把数据库提交放在循环外,减少数据库操作次数
- 数据库存储相对路径(供前端访问)而非嵌套的绝对路径
完整修正后的路由代码
@app.route('/upload-manga', methods=["POST", "GET"]) def upload(): ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) if current_user.is_authenticated: if request.method == "POST": pics = request.files name_characters = sample(ascii_letters+digits, 12) post_name = ''.join(name_characters) # 构建统一的目标目录绝对路径 target_dir = os.path.join(ROOT_DIR, 'static', post_name) os.makedirs(target_dir, exist_ok=True) # 创建README.txt with open(os.path.join(target_dir, 'README.txt'), 'w') as f: f.write('.') app.config["IMAGE_UPLOADS"] = target_dir mangaName = request.form['mangaName'] # 正确判断是否有上传的图片 uploaded_pics = pics.getlist('pic') if not uploaded_pics: return render_template('message.html', message="No images have been uploaded. ") sorted_pics = sorted(uploaded_pics, key=lambda x:int(x.filename.split('.')[0])) for pic in sorted_pics: filename = secure_filename(pic.filename) mimetype = pic.mimetype # 保存图片到目标目录 pic.save(os.path.join(app.config["IMAGE_UPLOADS"], filename)) # 存储相对路径到数据库,方便前端访问 img_location = os.path.join('static', post_name) image = Image( title=filename, mimetype=mimetype, img_location=img_location, post_name=post_name, user_id=current_user.id, manga_name=mangaName ) db.session.add(image) # 统一提交图片数据 db.session.commit() # 提交帖子记录 Post = Posts( user_id=current_user.id, post_name=post_name ) db.session.add(Post) db.session.commit() return render_template('message.html', message='The images have been uploaded') else: return render_template('upload.html') else: flash('You need to log in to upload images on this website') return redirect(url_for('login'))
额外优化点
- 使用
os.makedirs替代os.mkdir:支持自动创建多级父目录,避免因父目录缺失报错 - 用
with语句操作文件:自动关闭文件句柄,防止资源泄漏 - 批量提交数据库操作:减少数据库交互次数,提升性能
内容的提问来源于stack exchange,提问作者user21308041
相关产品推荐
相关产品推荐

