1. 程式人生 > >flask django 上傳檔案

flask django 上傳檔案

flask   上傳檔案

採用wtf 上傳檔案

設定表單:

class Up_file_Foem(FlaskForm):
    body = FileField(u'選擇上傳檔案', validators=[Required()])
    submit = SubmitField(u'開始上傳')

設定 前端頁面

@main.route('/', methods=['GET', 'POST'])  # 
def index():
    form = Up_file_Foem()
    print os.path.dirname(__file__)
    if form.validate_on_submit():
        file = form.body.data

        # filename = secure_filename(file.filename) #判斷檔名合法   但是當遇到中文時會導致檔名只剩字尾
filename = form.body.data.filename file.save(os.path.join(os.path.dirname(__file__), filename))#file是檔案流 save(所要儲存檔案的直接路徑) print '檔案儲存成功' else: print '---------------' return render_template('index.html', form=form)
前端頁面
    
{% extends "base.html" %}
{% import "bootstrap/wtf.html" 
as wtf %} {% import "_macros.html" as macros %} {% block title %}首頁{% endblock %} {% block page_content %} <div class="page-header"> <h1>歡迎</h1> </div> <div> {{ wtf.quick_form(form) }} </div> {% endblock %} {% block scripts %} {% endblock %}


django  上傳檔案

html  表單提交

<form enctype="multipart/form-data" method="POST" action="http://10.10.10.242:5000/EasyNode/v1/NODE/conversion_kvm/">
    <input type="text" name="a"> <br>
    <input type="file" name="myfile" /><br>
   <br />
   <input type="submit" value="上傳檔案" />
</form>

後臺獲取:

if request.method == 'POST':
    myFile = request.FILES.get("myfile", None)
    print request.POST['a']
    if os.path.exists(file_path + '/' + myFile.name):  # 判斷檔案是否重名
File_name = time.strftime('%Y_%m_%d', time.localtime(time.time())) + myFile.name
    else:
        File_name = myFile.name
    if not myFile:
        return HttpResponse(simplejson.dumps({'code': 1,'msg':'name repeat'}))
    try:
        destination = open(os.path.join(file_path, File_name), 'wb+')  # 儲存檔案
for chunk in myFile.chunks():  # 分塊寫入檔案
destination.write(chunk)
        destination.close()
    except:
        HttpResponse(simplejson.dumps({'code': 2,'msg':'save file erro'}))
    return HttpResponse(simplejson.dumps({'code': 0}))