Flask-Uploads IOError: [Errno 2] No such file or directory

Flask-Uploads IOError: [Errno 2] No such file or directory

所以,我一直在尝试将图片上传器添加到我的代码中,但我 运行 遇到了问题。尽管我认为我的 upload_folder 配置正确,但我不断收到类似以下的错误:IOError: [Errno 2] No such file or directory: '/static/uploads/compressor.jpg',即使 file/directory 存在。

代码如下:

在config.py

UPLOAD_FOLDER = 'static/uploads'

init.py

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

在views.py

@app.route('/fileupload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        #submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h>UPload new file</h1>
    <form action="" method=post enctype=multipart/form-data>
        <p><input type=file name=file>
            <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

我的文件夹结构如下

  /project folder
   --/app
   ----/static
   --------/uploads
   ----/templates
   ----_init__.py
   ----views.py
   --config.py

当我使用 /tmp/ 将其存储在内存中时,上传器工作正常。我假设它没有在寻找我的文件夹的正确路径。有人可以帮忙吗?我是一个非常业余的 python 开发者。

/tmp/static/uploads/..都是绝对路径。您的代码正在 / 文件夹中查找,而不是在项目文件夹中查找。您应该使用绝对路径指向您的文件夹 /path/to/your/project/static/uploads/.. 或使用相对于正在执行的代码的路径,例如 ./static/uploads.

您还可以使用以下代码片段生成绝对路径:

from os.path import join, dirname, realpath

UPLOADS_PATH = join(dirname(realpath(__file__)), 'static/uploads/..')

这对我有用:

basedir = os.path.abspath(os.path.dirname(__file__))

file.save(os.path.join(basedir, app.config['UPLOAD_FOLDER'], filename))

@jidesakin 的解决方案有效,但这是另一个解决方案:

将您的上传文件夹从静态目录移回您的应用程序文件夹所在的项目目录,即您的应用程序和环境文件夹所在的文件夹。

您的结构如下:

'projectfolder
--/app
      --config.py
      --__init__.py
------/static
------/templates
------config
--uploads

然后将上传文件夹的内容从 'static/uploads' 更改为 'uploads' ...