只需将文件保存到Django中的文件夹即可

Jon*_*Jon 11 python django django-models django-forms

我有一段代码通过POST从表单中获取文件.

file = request.FILES['f']
Run Code Online (Sandbox Code Playgroud)

将此文件保存到我的媒体文件夹的最简单方法是什么?

settings.MEDIA_ROOT
Run Code Online (Sandbox Code Playgroud)

我正在看这个答案,但其中有错误引用了未定义的名称和无效的"块"方法.

必须有一个简单的方法来做到这一点?

我的views.py中的EDIT上传方法:

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()
Run Code Online (Sandbox Code Playgroud)

Mes*_*sci 12

使用default_storage比更好FileSystemStorage

您可以将文件保存到MEDIA_ROOTFileSystemStorageDEFAULT_FILE_STORAGE将来更改后端时可能不再起作用。

如果您使用default_storage,将来如果您想将aws,azure等用作具有多个Django worker的文件存储,您的代码将可以正常运行而无需任何更改。

default_storage用法示例:

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)
Run Code Online (Sandbox Code Playgroud)


WKP*_*lus 7

你可以使用django FileField,它支持指定一个upload_to参数,如下所示:

data_file = models.FileField(upload_to=content_path)
Run Code Online (Sandbox Code Playgroud)

哪里content_path可以是字符串或返回字符串的函数.


bha*_*ipu 7

您可以将文件上传到Django服务器::

from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage

def upload(request):
    folder='my_folder/' 
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage(location=folder) #defaults to   MEDIA_ROOT  
        filename = fs.save(myfile.name, myfile)
        file_url = fs.url(filename)
        return render(request, 'upload.html', {
            'file_url': file_url
        })
    else:
         return render(request, 'upload.html')
Run Code Online (Sandbox Code Playgroud)