2011-08-01 12 views
-1

我試圖創建一個窗體,將處理來自用戶的視頻文件上傳,但我遇到了一堆問題。我試圖避免爲此構建模型表單,因爲我不會長期將文件保存到數據庫。我只想將它提交給服務器,以便我可以將其提交給YouTube。在HTML我有是:使用html和python處理文件提交

<form method='post' action='/new/' enctype="multi-part/form-data">{% csrf_token %} 
    <input type='file' name='file' id='file'/> 
    <input type='submit' /> 
</form> 

,然後視嘗試處理,像這樣的文件:

def create_video(request): 
    if request.method == 'POST': 
     video = request.POST['file'] 

     command=subprocess.Popen('youtube-upload --email=' + email + ' --password=' + password + '--title=' + title + ' --description=' + description + ' --category=Sports ' + video, stdout=subprocess.PIPE) 

     vid = command.stdout.read() 

     # do stuff to save video instance to database 
     return show_video(request, video.id) 
    else: 
     form=Video() 
    return render_to_response('create_video.html', RequestContext(request, locals())) 

注意:YouTube上傳是一個Python模塊,將視頻上傳到YouTube與給定的命令。

所以對於初學者來說,當我提出從前端Django的形式發送一個消息,說"Key 'file' not found in <QueryDict:...

,並給我固定的形式,這樣它會提交正確的觀點其餘妥善處理該文件?

+0

我希望你能理解與你正在做什麼相關的安全風險。 –

+0

說實話我沒有。就目前而言,這只是在本地主機上,我明白爲了不會造成安全風險,必須對其進行更改,但我希望首先對機制有一個基本的瞭解。如果你有替代方案來處理這個基本的過程,那麼我就會全神貫注。 –

+0

你不應該用用戶輸入調用系統命令。 –

回答

2

request.POST不包含文件上傳信息。您需要使用request.FILES

+0

非常感謝,但是現在我在'command = subprocess.Popen(youtube-upload --email = email --password = password --title ='+ title +'--description ='+ description +' --category = Sports'+ video,stdout = subprocess.PIPE)'。我強制轉換爲Unicode:需要字符串或緩衝區,找到InMemoryUploadedFile。我知道命令本身在終端工作。 –

+1

@DanLeaningphp,這是因爲'request.FILES'中的每個值都是['UploadedFile']的一個實例(https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.UploadedFile ),而不是路徑或類似的東西 - 實際上文件可能沒有寫入文件系統(足夠小的文件將存儲在內存中)。您應該閱讀[文件上傳](https://docs.djangoproject.com/en/dev/topics/http/file-uploads/)上的文檔 - 可能您希望將該文件的內容保存到磁盤在某處,然後運行你的命令,然後刪除它。 –