简体   繁体   English

如何在 flask 中制作上传文件

[英]how can I make a upload file in flask

This is my upload function but every time I go to addclothes route and adding image into the form then I got this error:这是我上传的 function 但每次我addclothes添加衣服路线并将图像添加到表单中时,我都会收到此错误:这是错误

I know is my path problem but I don't know how to put the file in the base directory我知道是我的路径问题,但我不知道如何将文件放在基目录中

@app.route('/addclothes', methods=["POST","GET"])
def addclothes():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file :
            filename = secure_filename(file.filename)
            file.save(os.path.join('/static/img/',filename))

            new_clothes = Clothes(clothesname=clothesname,image=image,price=price,isSuperUser=False)
            db.session.add(new_clother)
            db.session.commit()
            
            return redirect(url_for('addclothes'))



    return render_template('addclothes.html')

This is my file structure:这是我的文件结构:

文件结构

I want to add it to base directory我想将它添加到基本目录

You should save this with:你应该保存这个:

file.save(os.path.join('static/img/',filename))

Note the removal of the preceding / before static.注意前面的/之前 static 的删除。 With this present it is trying to save to a static subdirectory on the / drive of the server , not within the app's directory.有了这个礼物,它试图保存到服务器/驱动器上的static子目录中,而不是在应用程序的目录中。

On a side note, it may be to your advantage to make a filename containing random characters, rather than using the user-provided filename;附带说明一下,创建包含随机字符的文件名可能对您有利,而不是使用用户提供的文件名; certainly if you're handling a large number of file uploads.当然,如果您要处理大量文件上传。 See another thread I wrote regarding avoiding duplicate filenames .请参阅我写的关于避免重复文件名的另一个线程。

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

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