python3 flask实现文件上传功能

yipeiwu_com6年前Python基础

本文实例为大家分享了python3-flask文件上传操作的具体代码,供大家参考,具体内容如下

# -*- coding: utf-8 -*-
import os
import uuid
import platform
from flask import Flask,request,redirect,url_for
from werkzeug.utils import secure_filename

if platform.system() == "Windows":
  slash = '\\'
else:
  platform.system()=="Linux"
  slash = '/'
UPLOAD_FOLDER = 'upload'
ALLOW_EXTENSIONS = set(['html', 'htm', 'doc', 'docx', 'mht', 'pdf'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#判断文件夹是否存在,如果不存在则创建
if not os.path.exists(UPLOAD_FOLDER):
  os.makedirs(UPLOAD_FOLDER)
else:
  pass
# 判断文件后缀是否在列表中
def allowed_file(filename):
  return '.' in filename and \
      filename.rsplit('.', 1)[1] in ALLOW_EXTENSIONS

@app.route('/',methods=['GET','POST'])
def upload_file():
  if request.method =='POST':
    #获取post过来的文件名称,从name=file参数中获取
    file = request.files['file']
    if file and allowed_file(file.filename):
      # secure_filename方法会去掉文件名中的中文
      filename = secure_filename(file.filename)
      #因为上次的文件可能有重名,因此使用uuid保存文件
      file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
      file.save(os.path.join(app.config['UPLOAD_FOLDER'],file_name))
      base_path = os.getcwd()
      file_path = base_path + slash + app.config['UPLOAD_FOLDER'] + slash + file_name
      print(file_path)
      return redirect(url_for('upload_file',filename = file_name))
  return '''
  <!doctype html>
  <title>Upload new File</title>
  <h1>Upload new File</h1>
  <form action="" method=post enctype=multipart/form-data>
   <p><input type=file name=file>
     <input type=submit value=Upload>
  </form>
  '''
if __name__ == "__main__":
  app.run(host='0.0.0.0',port=5000)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 统计文件中的字符串数目示例

题目: 一个txt文件中已知数据格式为: C4D C4D/maya C4D C4D/su C4D/max/AE 统计每个字段出现的次数,比如C4D、maya 先读取文件,将文件中的数据抽...

python 性能优化方法小结

python 性能优化方法小结

提高性能有如下方法 1、Cython,用于合并python和c语言静态编译泛型 2、IPython.parallel,用于在本地或者集群上并行执行代码 3、numexpr,用于快速数值运...

Python3之字节串bytes与字节数组bytearray的使用详解

字节串bytes 字节串也叫字节序列,是不可变的序列,存储以字节为单位的数据 字节串表示方法: b"ABCD" b"\x41\x42" ... 字节串的构造函数: bytes()...

python读取浮点数和读取文本文件示例

从文本文件中读入浮点数据,是最常见的任务之一,python没有scanf这样的输入函数,但我们可以利用正规表达式从读入的字符串中提取出浮点数 复制代码 代码如下:import refp...

Python获取当前页面内所有链接的四种方法对比分析

本文实例讲述了Python获取当前页面内所有链接的四种方法。分享给大家供大家参考,具体如下: ''' 得到当前页面所有连接 ''' import requests import re...