在Django中接收檔案並儲存

2021-09-12 02:49:02 字數 1411 閱讀 2215

首先是乙個views函式的例子

defget_user_profiles(request):ifrequest.method == 'post':

myfile = request.files.get("filename",none)ifmyfile:

dir = os.path.join(os.path.join(base_dir, 'static'),'profiles')

destination = open(os.path.join(dir, myfile.name),

'wb+')forchunkinmyfile.chunks():

destination.write(chunk)

destination.close()returnhttpresponse('ok')

這是乙個簡單的接收客戶端上傳的頭像檔案並儲存的例子,應該看過這個就已經大體會使用接收檔案了

但是這裡的filename是客戶端上傳的檔名,也可能是像下面這樣的表單

"file" name="filename" />
如果不知道固定上傳的檔名,想要客戶端上傳什麼檔案就以其上傳的名字命名可以這麼寫

defget_user_profiles(request):ifrequest.method == 'post':ifrequest.files:

myfile =noneforiinrequest.files:

myfile = request.files[i]ifmyfile:

dir = os.path.join(os.path.join(base_dir, 'static'),'profiles')

destination = open(os.path.join(dir, myfile.name),

'wb+')forchunkinmyfile.chunks():

destination.write(chunk)

destination.close()returnhttpresponse('ok')

不過這個是通過輸出request.files試出來的,不知道是否有更合適的方法。

在Linux使用SFTP接收檔案

安全檔案傳輸協議 secure file transfer protocol sftp 是乙個檔案傳輸程式通過ssh通道和使用ssh的多數特徵。包含壓縮和加密。本質上來說。sftp是乙個深度替換標準的命令列ftp客戶端。但是使用的ssh的理論。開啟sftp starting sftp 開始的命令如下...

在django中引用html檔案

使用記事本或者idea寫好乙個html檔案 pycharm 命令提示符 在命令提示符中使用以下 建立完成後,將自己寫好的html檔案複製到該資料夾內,這裡我使用的html檔名為creat 如下 def hello request return render request,creat.html 如下...

Django在view中讀取txt檔案

在view中想載入乙個block words的txt來遮蔽髒字。但是一直報錯找不到檔案 使用完整路徑,把txt放在view.py同一路徑下,加入前兩行即可 module dir os.path.dirname file file path os.path.join module dir,block ...