简体   繁体   English

Flask - 为什么这不能让我导入图像文件?

[英]Flask - Why doesn't this let me import image files?

I am trying to make an application that allows users to upload images from their computer.我正在尝试制作一个允许用户从他们的计算机上传图像的应用程序。 This is as part of my CS50x final project, so I'm working in the CS50 IDE.这是我的 CS50x 最终项目的一部分,所以我在 CS50 IDE 中工作。 Here is the code for my application:这是我的应用程序的代码:

application.py应用程序.py

import os
from flask import *  
app = Flask(__name__)  

UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER     
 
@app.route('/')  
def myindex():
    return render_template("file_upload_form.html")  
 
@app.route('/upload', methods = ['POST'])  
def upload():  
    if request.method == 'POST':  
        file = request.files['file']  
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], "test.jpg"))
        return redirect("/")
        
if __name__ == "__main__":
    app.run(debug=True)

file_upload_form.html file_upload_form.html

<html>  
<head>  
    <title>upload</title>  
</head>  
<body>  
    <form action = "/upload" method = "post" enctype="multipart/form-data">  
        <input type="file" name="file" />  
        <input type = "submit" value="Upload">  
    </form>  
</body>  
</html>  

For the vast majority of files, when I submit the form, I get a 500 Internal Server Error with no traceback or explanation.对于绝大多数文件,当我提交表单时,我会收到500 内部服务器错误,没有回溯或解释。 Curiously though, some files it seems to work with.不过奇怪的是,它似乎可以处理一些文件。 I have found two images that work: both JPEGs and both relatively small.我发现了两个有效的图像:JPEG 和相对较小的图像。 All other images I have tried have caused the error.我尝试过的所有其他图像都导致了错误。

I cannot work out what is causing the Server Error, or why some images work and others don't.我无法弄清楚导致服务器错误的原因,或者为什么某些图像有效而其他图像无效。 Can anyone see any reason why it wouldn't work for other images?谁能看到它不适用于其他图像的任何原因?

Thanks谢谢

You are sending the post to: <form action = "/success"...>您将post发送至: <form action = "/success"...>

Where is your /success handler?您的/success处理程序在哪里?

UPDATE:更新:

Try:尝试:

if request.method == 'POST':  
    print(request.files)
    print(request.form)
    print(request.POST)

You need to check the logs to see what there error is.您需要检查日志以查看有什么错误。

I tested out your code and it worked fine on my side, but there is a couple of additions i would make, just to make it more robust.我测试了你的代码,它在我这边运行良好,但我会做一些补充,只是为了让它更健壮。

You are calling all your uploads test.jpg and there is no mechanism in place to ensure that the file that gets uploaded is a jpg file.您正在调用所有上传的 test.jpg 并且没有适当的机制来确保上传的文件是 jpg 文件。 So technically, i could upload a pdf and it would be renamed in to a test.jpg.所以从技术上讲,我可以上传 pdf 并将其重命名为 test.jpg。 A better method is to just give the file - the same name it had, including the extension.一个更好的方法是只给文件 - 它的名称相同,包括扩展名。 If you want to re-name the file, rather strip the extension first and add it to the new filename like so:如果要重命名文件,请先删除扩展名并将其添加到新文件名中,如下所示:

ext = file.filename.rsplit('.', 1)[1].lower()
newFilename = 'newname.{}'.format(ext)

Also there is no MAX_CONTENT_LENGTH - I would add that as well.也没有 MAX_CONTENT_LENGTH - 我也会添加它。

So i re-wrote your python code to look like this:所以我重新编写了您的 python 代码,如下所示:

import os
from flask import *
from werkzeug.utils import secure_filename

app = Flask(__name__)

UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['ALLOWED_IMAGES'] = set(['png', 'jpg', 'jpeg'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

def allowed_image(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_IMAGES']

@app.route('/')
def myindex():

    return render_template("index.html")

@app.route('/upload', methods = ['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']

        if file and allowed_image(file.filename):

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(file.filename)))
            return redirect(request.url)



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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM