【问题标题】:Flask, Python: File is not saving in the folder "images"Flask,Python:文件未保存在“图像”文件夹中
【发布时间】:2017-08-12 03:47:35
【问题描述】:

我正在尝试创建名为“images”的新文件夹,并将文件 [来自 upload.html] 的文件保存在“images”文件夹中。我的问题是,正在生成文件夹,但文件没有保存到文件夹中。请参阅下面的附加代码。

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Convert csv to JSON</title>
</head>
<body>
<form action="{{url_for('upload')}}" method="post" enctype="multipart/form-data">
<input type="file" name="upload" accept="image/"/>
<input type="submit" /></form>

</body>
</html>

在控制台输出的是:

E:/images
<FileStorage: u'I-94.pdf' ('application/pdf')>
('Accept incoming file:', u'I-94.pdf')
E:/images/I-94.pdf

  File "E:\datamining\tryproject\convert.py", line 32, in upload
    upload.save(destination)
AttributeError: 'function' object has no attribute 'save'

python代码如下所示

convert.py

import os

from flask import Flask, request, render_template, send_from_directory

__author__ = 'praveen'

app = Flask(__name__)

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


@app.route("/")
def index():
    return render_template("upload.html")


@app.route("/upload", methods=["POST"])
def upload():

    target = os.path.join(APP_ROOT, '/images')
    print(target)
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("upload"):
        print(file)

        filename = file.filename
        destination = "/".join([target, filename])
        print("Accept incoming file:", filename)
        print(destination)
        upload.save(destination)  

if __name__ == "__main__":
    app.run(port=4555, debug=True)

【问题讨论】:

  • upload 是视图函数的名称,而不是文件对象。
  • @stamaimer 非常感谢您的建议。现在工作正常。
  • @eyllanesc 我进行了更正并发布了正确答案。

标签: python python-2.7 python-3.x flask


【解决方案1】:
convert.py

import os

from flask import Flask, request, render_template, send_from_directory

__author__ = 'praveen'

app = Flask(__name__)

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


@app.route("/")
def index():
    return render_template("upload.html")


@app.route("/upload", methods=["POST"])
def upload():

    target = os.path.join(APP_ROOT, '/images')
    print(target)
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("upload"):
        print(file)

        filename = file.filename
        destination = "/".join([target, filename])
        print("Accept incoming file:", filename)
        print(destination)
        file.save(destination)   //i made change here

if __name__ == "__main__":
    app.run(port=4555, debug=True)

【讨论】:

    【解决方案2】:

    从这里删除一个斜线:

    target = os.path.join(APP_ROOT, '/images')
    

    所以它会是:

    target = os.path.join(APP_ROOT, 'images')
    

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2021-08-12
      • 2019-09-03
      • 2014-12-11
      相关资源
      最近更新 更多