Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

python - Simply save file to folder in Django

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?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using default_storage is better than FileSystemStorage.

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.

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 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...