python3 flask实现文件上传功能

yipeiwu_com5年前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设计】。

相关文章

Selenium chrome配置代理Python版的方法

环境: windows 7 + Python 3.5.2 + Selenium 3.4.2 + Chrome Driver 2.29 + Chrome 58.0.3029.110 (64...

Python 中urls.py:URL dispatcher(路由配置文件)详解

Python 中urls.py:URL dispatcher(路由配置文件)详解

urls.py:URL dispatcher(路由配置文件) URL配置(URLconf)就像是Django所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的...

python读取并定位excel数据坐标系详解

python读取并定位excel数据坐标系详解

测试数据:坐标数据:testExcelData.xlsx 使用python读取excel文件需要安装xlrd库: xlrd下载后的压缩文件:xlrd-1.2.0.tar.gz 解压后再...

python实现统计代码行数的小工具

python实现统计代码行数的小工具

一个用python实现的统计代码行数的小工具,供大家参考,具体内容如下 实现功能 计算出某一目录以及子目录下代码文件的行数 在计算代码的过程中,只对标准命名的文件进行统计,如[...

Python进程通信之匿名管道实例讲解

匿名管道 管道是一个单向通道,有点类似共享内存缓存.管道有两端,包括输入端和输出端.对于一个进程的而言,它只能看到管道一端,即要么是输入端要么是输出端. os.pipe()返回2个文件描...