只需将文件保存到Django中的文件夹 [英] Simply save file to folder in Django

查看:160
本文介绍了只需将文件保存到Django中的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码可以通过POST从表单获取文件。

I have a piece of code which gets a file from a form via POST.

file = request.FILES['f']

将文件保存到我的媒体文件夹中最简单的方法是

What would be the simplest way of saving this file to my media folder in

settings.MEDIA_ROOT

我正在查看这答案等,但是我在引用未定义名称和无效的块方法时遇到了错误。

I was looking at this answer, among others, but I had errors refering to undefined names and invalid "chunks" method.

必须有一种简单的方法吗?

There must be a simple way to do this?

编辑
我的views.py中的上传方法:

EDIT Upload method in my views.py:

def upload(request):
    folder = request.path.replace("/", "_")
    uploaded_filename = request.FILES['f'].name

    # create the folder if it doesn't exist.
    try:
        os.mkdir(os.path.join(settings.MEDIA_ROOT, folder))
    except:
        pass

    # save the uploaded file inside that folder.
    full_filename = os.path.join(settings.MEDIA_ROOT, folder, uploaded_filename)
    fout = open(full_filename, 'wb+')

    file_content = ContentFile( request.FILES['f'].read() )

    # Iterate through the chunks.
    for chunk in file_content.chunks():
        fout.write(chunk)
    fout.close()


推荐答案

使用 default_storage 优于 FileSystemStorage

您可以使用 FileSystemStorage 将文件保存到 MEDIA_ROOT 当您将来更改 DEFAULT_FILE_STORAGE 后端时,此功能可能不再起作用。

You can save file to MEDIA_ROOT with FileSystemStorage but when you change DEFAULT_FILE_STORAGE backend in the future this may not work anymore.

如果使用 default_storage ,将来如果要使用AWS,Azure等作为具有多个文件存储的文件存储Django工作者,您的代码将保持不变。

If you use default_storage, in the future if you want to use aws, azure etc as file store with multiple Django worker your code will work without any change.

default_storage用法示例:

default_storage usage example:

from django.core.files.storage import default_storage

#  Saving POST'ed file to storage
file = request.FILES['myfile']
file_name = default_storage.save(file.name, file)

#  Reading file from storage
file = default_storage.open(file_name)
file_url = default_storage.url(file_name)

这篇关于只需将文件保存到Django中的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆