2015-06-15 52 views
2

我會說,我對Flask非常新(這是我的第一個項目),我有興趣在黑客攻擊它,而不是最佳做法。Flask奇怪的行爲w /文件夾創建/文件上傳

我目前的代碼無法在圖片目錄中創建用戶命名的文件夾。我已經嘗試過在這裏尋找一些答案,但無濟於事,我可以讓這三件事情協調一致地工作。這是有問題的功能。

@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) 
      foo = request.form.get('name') 
      if not os.path.exists("/pictures/directory"): os.makedirs("/pictures"+foo) 
      app.config["UPLOAD_FOLDER"] = "/pictures" + foo 
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
    else: 
     return render_template("upload.html") 
    return render_template("index.html") 

如果任何人有興趣也考慮看看爲什麼upload.html使得第一(預計),但「繼續」按鈕無法呈現的index.html,我會非常感激。

這裏的回購,如果任何人的好奇,它的其餘部分:https://bitbucket.org/dillon9/ss

編輯1:感謝你們倆我有一個半功能前端和一個功能齊全的後端。新代碼被推送。希望我可以接受你的兩個答案

回答

1

這是因爲你的foo變量不包含用戶給出的值。你第一次得到您的用戶與

foo = request.form.get('name') 

指定的名稱,但然後立即使用它

foo = "/directory/" 

編輯之前分配給同一個變量別的東西:現在可能正在使用C創建目錄:\ 或者其他的東西。將代碼更改爲這樣的代碼

@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) 
       foo = request.form['name'] 
       path = os.path.dirname(os.path.abspath(__file__)) + "/pictures/"+foo 
       if not os.path.exists(path):   
        os.makedirs(path) 
       app.config["UPLOAD_FOLDER"] = path 
       file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
     else: 
      return render_template("upload.html") 
     return render_template("index.html") 
+0

哈哈我完全忘了把它放在這裏,第二個foo任務是用於調試以測試實際上可以創建的文件夾。很好,我會編輯 –

+0

你能保存圖片嗎? –

+0

沒有什麼能夠一起工作,我不是超級擔心它的上傳部分,因爲它已經在過去工作,只是沒有這個當前代碼 –

2

代碼中有幾件事需要更改。

第一:

通常根頁"/"被映射到一個名爲index功能。

@app.route('/', methods = ["GET","POST"]) 
def index(): 
    if request.method == 'POST': 
     file = request.files['file'] 
     if file and allowed_file(file.filename): 
      filename = secure_filename(file.filename) 
      foo = request.form.get('name') 
      if not os.path.exists("/pictures/directory"): 
       os.makedirs("/pictures"+foo) 
      app.config["UPLOAD_FOLDER"] = "/pictures" + foo 
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
    else: 
     return render_template("upload.html") 
    return render_template("index.html") 

二:

它將使使用單一的按鈕更有意義 - 在這種情況下Update - 用於更新內容和重定向,那麼你可以放棄Continue按鈕。

三:

upload.html文件必須更正表單代碼

<form action="" method=post enctype=multipart/form-data> 

<form action="{{ url_for("index") }}" method= "post" enctype= "multipart/form-data"> 

所以你給action屬性爲一個值處理這種形式的函數的url。最後,在值的周圍添加雙引號。