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

相关文章

Python中利用sorted()函数排序的简单教程

排序算法 排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大...

python实现备份目录的方法

本文实例讲述了python实现备份目录的方法。分享给大家供大家参考。具体如下: 备份脚本1: #!/usr/bin/python # Filename: backup_ver1.py...

django基础学习之send_mail功能

前言 我们知道python中smtplib模块用于邮件的功能,而django对这个这模块进行封装,使得它使用起来十分简单。 django.core.mail就是django邮件的核心模...

深入浅析Python中的迭代器

深入浅析Python中的迭代器

目录结构: contents structure [-] 在开始文章之前,先贴上一张Iterable、Iterator与Generator之间的关系图:   1. Itera...

使用TensorFlow实现SVM

使用TensorFlow实现SVM

较基础的SVM,后续会加上多分类以及高斯核,供大家参考。 Talk is cheap, show me the code import tensorflow as tf from s...