注意

  • 一个

    标签被标记有 enctype=multipart/form-data ,并且在里面包含一个 标签

  • 服务器端应用通过请求对象上的 file 字典访问文件

  • 使用文件的save()方法将文件永久保存在文件系统的某处
  • windows 和linux 下路径分割符不一样,使用绝对路径时候 会报错

    导入包

    1. from flask import Flask,render_template,request
    2. import os
    3. from os import path
    4. from werkzeug.utils import secure_filename
    5. #
  • os.path.sep : windows \

  • os.path.altsep :linux /
  • 根目录:os.path.
  • 当前目录:os.path.curdir
  • 父目录:os.path.padirpr
  • 绝对路径: os.path.join()

基本文件上传

要提前建好uploads 目录,不然会报错

  1. import fileinput
  2. from flask import Flask,render_template,request
  3. import os
  4. from os import path
  5. from werkzeug.utils import secure_filename
  6. app=Flask(__name__)
  7. @app.route('/',methods=['GET','POST'])
  8. def hello_word():
  9. if request.method=='GET':
  10. return render_template('upload.html')
  11. else:
  12. f=request.files['file']
  13. filename=secure_filename(f.filename)
  14. f.save(path.join('static/uploads',filename))
  15. return "upload success"
  16. if __name__ == '__main__':
  17. app.run(debug=True)

upload.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>file upload</title>
  6. <style type="text/css">
  7. .div1{
  8. height: 180px;
  9. width: 380px;
  10. border: solid #8A8989;
  11. margin: 0 auto;
  12. }
  13. .input{
  14. display: block;
  15. width: 250px;
  16. height: 30px;
  17. margin: 0 auto;
  18. }
  19. .button{
  20. background: #2066C5;
  21. color: white;
  22. font-weight: bold;
  23. font-size: 18px;
  24. border-radius: 4px;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <div class="div1">
  30. <form action="" method="post" enctype="multipart/form-data">
  31. <input type="file" name="file" class="input">
  32. <input type="submit" value="upload" class="button">
  33. </form>
  34. </div>
  35. </body>
  36. </html>

image.png

功能改进

  • 防止上传文件名相同,对文件重命名
  • uploads 保存文件夹,不存在时自动创建
  • 对文件进行格式校验,防止上传恶意文件 ```python import fileinput import time import platform from flask import Flask,render_template,request,send_from_directory import os from os import path from werkzeug.utils import secure_filename from wtforms import Form,FileField,StringField from wtforms.validators import InputRequired from flask_wtf.file import FileRequired,FileAllowed from werkzeug.datastructures import CombinedMultiDict

class UploadForm(Form): file=FileField(validators=[FileRequired(),FileAllowed([‘jpg’,’png’])])

app=Flask(name) if platform==’Windows’: slash=’\‘ uploadpath =os.path.curdir+os.path.sep+’uploads’+os.path.sep

@app.route(‘/‘,methods=[‘GET’,’POST’]) def hello_word(): if request.method==’GET’: return render_template(‘upload.html’) else: if not os.path.exists(uploadpath): os.mkdir(uploadpath) form=UploadForm(CombinedMultiDict([request.form,request.files]))

    if form.validate():
        f=request.files['file']
        filename=secure_filename(f.filename)
        ext=filename.rsplit('.',1)[1]
        unix_time=int(time.time())
        new_filename=str(unix_time)+'.'+ext

        file_url=uploadpath+new_filename
        f.save(path.join(uploadpath,new_filename))
        return "upload success"
    else:
        return "only support jpg"

@app.route('/images/<filename>/',methods=['GET','POST'])
def get_image(filename):
    dirpah=os.path.join(app.route_path,'uploads')
    return send_from_directory(dirpah,filename,as_attachment=True)

if name == ‘main‘: app.run(debug=True)


<a name="xCWPT"></a>
## 下载文件
```python
@app.route('/images/<filename>/',methods=['GET','POST'])
    def get_image(filename):
        dirpah=os.path.join(app.route_path,'uploads')
        return send_from_directory(dirpath,filename,as_attachment=True)