我一直在尋找很多類似的問題,都在Google和StackOverflow上,但似乎沒有一個滿意的解決方案適用於我。將文件寫入Django服務器上的動態路徑
我的情況是這樣的 -
我使用jQuery File Upload以下步驟here。
我想要保存文件的位置是動態的,它取決於username
和session_key
。
這是寫文件的功能 -
def handle_uploaded_file(file, session_key, username):
folder_path = os.path.dirname(os.path.realpath(__file__)) + '\\Source\\' + username + '\\session_id_' + session_key
if not os.path.exists(folder_path):
os.makedirs(folder_path)
save_path = folder_path + '\\Source Files'
with open(save_path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
我試着上傳了一個名爲「normal.csv」的文件,而是我有一個名爲「源文件」文件沒有目錄內的延伸。
當我改變了open()
函數內部的路徑
with open(save_path+file.name, 'wb+') as destination
我有一個名爲「源Filesnormal.csv」文件。
然後我試圖改變save_path
到folder_path + '\\Source Files\\'
,並在save_path+file.name
傳遞給open()
,但隨後又說No such file or directory
。
我很困惑如何進入該文件夾位置並寫入文件。
這裏我不能使用MEDIA_URL
,因爲它取決於username
和session_key
。
使用'os.path.join'來獲取您的目標路徑。字符串連接不是達到這個目的的好方法。 – ohannes