Flask Note: File Upload

File Upload

  • enctype: in HTML form form form tag default `enctype =" application / x- www-form-urlencoded "`, when the file upload should be set to `enctype =" multipart / form- data "`, otherwise the file Upload will not succeed.
  • Get upload files background: FileObj = request.files.get ( 'input_file_name'), to note that the method of parameter get is the HTML file input tag specifies the name attribute value, rather than the file name to upload.
  • File name handling: Use fileobj.filename to get to the file name, but does not recommend the use of the file name directly, for security reasons, it is recommended to use from werkzeug.utils import secure_filename file name filter to handle it.
  • Save the file: the Save method of using the returned file object to, fileobj.save (file_path), file_path is the absolute path to save the file.
  • Send files back to the browser: Use from flask import send_from_directory, return directly to the corresponding file, send_from_directory requires two parameters, the first parameter is the file directory, and the second parameter is the file name.

 

File validation

  • Form validation: using a subclass from wtforms import Form verified.
  • Field type: from WTForms Import FileField, FileField the file type.
  • Validator: from flask_wtf.file Import FileRequired, FileAllowed, FileRequired indicates that the file can not be empty, FileAllowed indicate the type of file extension.
  • Multi-element combination: request There are many types of files, and text and other elements, the data acquired from the request in a manner not at the same time, such as: request.form and request.files, and then want to use the Form object form validation, We need to use from werkzeug.datastructures import CombinedMultiDict will combine a variety of elements, and then pass the form object to verify.
  • Data acquisition: After verification after the form object, can obtain data such as text files and by "form [attr_name] .data." Manner, in this way, and the data acquired by the request is the same.

 

A simple example:

HTML file upload.html the main code

 <form action="" method="post" enctype="multipart/form-data">
        <table>
            <tbody>
                <tr>
                    <td>头像:</td>
                    <td><input type="file" name="avatar"></td>
                </tr>
                <tr>
                    <td>描述:</td>
                    <td><input type="text" name="desc"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="提交"></td>
                </tr>
            </tbody>
        </table>
    </form>

Browser effect

Form object file forms.py

from WTForms Import Form1, the FileField, StringField
 from wtforms.validators Import InputRequired
 from flask_wtf.file Import FileRequired, FileAllowed 


class UploadFileForm (Form1):
     # the FileField the field indicating the file type 
    Avatar = the FileField (validators = [FileRequired (), FileAllowed ([ ' JPG ' , ' PNG ' , ' GIF ' ])])
     # StringField field representing a string type 
    desc = StringField (validators = [InputRequired ()])

 

 Main py file

import os
from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict
from flask import Flask, request, render_template, send_from_directory
from forms import UploadFileForm

app = Flask(__name__)

# 所有图片文件放在根目录的images文件夹下
UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'images')


@app.route('/upload/', methods=['GET' , ' The POST ' ])
 DEF Upload ():
     IF request.method == ' the GET ' :
         return the render_template ( ' upload.html ' )
     the else :
         # binding request plurality of form elements in the form 
        form = UploadFileForm (CombinedMultiDict ([ Request.Form, request.FILES]))
         IF form.validate ():
             # acquires the corresponding data uploaded in accordance with the corresponding html tag name attribute 
            # Request.Form equivalent to a dictionary 
            # desc = request.form.get ( 'desc ') 
            desc =form.desc.data
             Print (desc)
             # obtain files from request.files need to get the 
            # Avatar = request.files.get ( 'Avatar') 
            Avatar = form.avatar.data
             # To be safe, you need to use a special file name way (secure_filename function) filtering at 
            # secure_filename for Chinese support is not very good, you can convert the file name, but still recommended to use this function to deal with what 
            filename = secure_filename (avatar.filename)
             # file object returned by direct it's save method to save the incoming path, the path can not be a relative path, an absolute path is required 
            avatar.save (os.path.join (upload_path, filename))
             return  ' file uploaded successfully! ' 
        The else :
             Print (form.errors)
            return  ' file upload failed! ' 


@ App.route ( ' / ImagesRF Royalty Free / <filename> / ' )
 DEF get_image (filename):
     # get the file back to the browser using send_from_directory, the first parameter is the file directory, and the second parameter is the file name 
    return send_from_directory (upload_path, filename) 


IF  the __name__ == ' __main__ ' : 
    app.run (Debug = True)

 

Guess you like

Origin www.cnblogs.com/guyuyun/p/11223447.html