windows下Flask上传文件路径

时间:2022-08-09 05:55:47

在windows下用Flask实现图片上传,上传后总是找不到正确的文件夹路径。修改上传文件夹为如下的时候:

<span style="font-size:18px;">UPLOAD_FOLDER =</span>sys.path[0]

上传到程序所在的当前文件夹,但是添加了当前路径下的文件夹后就会出错,试过了各种组合,最后找到了一个很好的并且可以随意任何操作系统之间迁移的方法:

python中os.path常用模块:os.path.sep路径分隔符 ,linux下就用这个了’/’os.path.altsep:

根目录:os.path.curdir

当前目录:os.path.pardir

父目录:os.path.abspath(path)

绝对路径:os.path.join()

常用来链接路径:os.path.split(path),把path分为目录和文件两个部分,以列表返回

修改后程序如下图:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")      //设置默认编码为UTF-8可以正常显示中文
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
from flask import send_from_directory
import os.path

UPLOAD_FOLDER =os.path.curdir+os.path.sep+'tmp'+os.path.sep      //该路径为当前文件夹拼接windows下文件分隔符再拼接‘tmp'文件夹,再拼接文件分隔符


ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])  //允许上传的图片类型

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data> <!--只要确保你没忘记在 HTML 表单中设置<tt class="docutils literal"><span class="pre">enctype="multipart/form-data"</span></tt> 属性,不然你的浏览器根本不会发送文件。-->
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
	'''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)
	
if __name__=='__main__':  
    app.run(debug=True)  


1.只要确保你没忘记在 HTML 表单中设置<tt class="docutils literal"><span class="pre">enctype="multipart/form-data"</span></tt> 属性,不然你的浏览器根本不会发送文件。