【问题标题】:Writing file to a dynamic path on the server in Django在Django中将文件写入服务器上的动态路径
【发布时间】:2017-08-31 07:08:54
【问题描述】:

我在 Google 和 StackOverflow 上都查看了很多类似的问题,但似乎没有适合我的令人满意的解决方案。

我的情况是这样的——

我正在按照here 的步骤使用jQuery File Upload

我要保存文件的位置是动态的,它取决于usernamesession_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”的文件,但我得到了一个名为“Source Files”的文件,目录中没有扩展名。

当我将 open() 函数内的路径更改为

with open(save_path+file.name, 'wb+') as destination

我有一个名为“Source Filesnormal.csv”的文件。

然后我尝试将save_path 更改为folder_path + '\\Source Files\\',并将save_path+file.name 传递给open(),但随后显示No such file or directory

我很困惑如何进入该文件夹位置并写入文件。

我不能在这里使用MEDIA_URL,因为它依赖于usernamesession_key

【问题讨论】:

  • 使用os.path.join 获取您的目标路径。字符串连接不是实现此目的的好方法。

标签: python django io


【解决方案1】:

您没有将上传的文件名指定给目标路径。

应该是这样的:

save_path = os.path.join(folder_path, 'Source Files', file.name)

你会给你这样的路径:

...\Source Files\your_uploaded_file_name

但是,请记住,您需要检查此路径中是否存在目录。所以,os.path.exists 检查 'Source Files' 会很好。

source_files_path = os.path.join(folder_path, 'Source Files')

if not os.path.exists(source_files_path):
    os.mkdirs(source_files_path)

save_path = os.path.join(source_files_path, file.name)

【讨论】:

  • 好的,谢谢。我多么愚蠢。我完全忘记检查嵌套目录。
  • 你知道,它发生了。很高兴它有帮助。
猜你喜欢
  • 2014-08-11
  • 2011-07-05
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
相关资源
最近更新 更多