標籤:enc rand 邏輯 錯誤 class 模版 file name cti
近日在用Django架構開發過程中遇到上傳帳戶圖片問題,經多方搜尋資料,終於解決問題!
1.首先,在html模版中添加類似下面的代碼
| 12345 |
<form enctype="multipart/form-data" method="POST" action="/view/process/upload/file"> {% csrf_token %} <input type="file" name="your_file"/> <input type="submit" value="上傳檔案" /></form> |
這裡需要注意一下幾點:
- form表單匯總一定要有enctype="multipart/form-data"屬性
- form需要以POST方式提交
- form的Action屬性對應views中處理upload上傳邏輯的函數
- 需要有csrf_token這個標籤,否則post無法提交
- 第一個<input>的類型為file,這是一個檔案選取器,name屬性很重要,因為後面通過此欄位取出檔案對象
2.接下來,編寫CGI邏輯
| 1234567891011121314 |
def process_upload_file(request): # 擷取檔案 file_obj = request.FILES.get(‘your_file‘, None) if file_obj == None: return HttpResponse(‘file not existing in the request‘) # 寫入檔案 file_name = ‘temp_file-%d‘ % random.randint(0,100000) # 不能使用檔案名稱,因為存在中文,會引起內部錯誤 file_full_path = os.path.join(UPLOAD_ROOT, file_name) dest = open(file_full_path,‘wb+‘) dest.write(file_obj.read()) dest.close() return render_to_response(‘upload_result.html‘,{}) |
取用檔案的方式為:“file_obj = request.FILES.get(‘file‘, None)”。第一個參數”your_file”對應form中的第一個input標籤。然後,可以通過file_obj.name擷取檔案名稱,file_obj.read()方法擷取檔案內容。上傳的檔案放在記憶體中,所以此方法只適合小檔案上傳。
Django檔案上傳執行個體