Jon
Jon

Reputation: 3204

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

Upvotes: 50

Views: 86652

Answers (4)

Tobias Ernst
Tobias Ernst

Reputation: 4654

Use the following code to update a FileField or ImageField. Django will upload the file to settings.MEDIA_ROOT per default.

from os.path import basename
from django.core.files import File
self.model.file_field.save(basename(path), content=File(open(path, 'rb')))

Afterwords you can access:

The path like this:

self.model.file_field.path

The url like this:

self.model.file_field.url

Upvotes: 2

Mesut Tasci
Mesut Tasci

Reputation: 3130

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)

Upvotes: 67

bhawnesh dipu
bhawnesh dipu

Reputation: 1322

you can upload files to django server : :

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

Upvotes: 25

WKPlus
WKPlus

Reputation: 7255

You can use django FileField, it support specify a upload_to parameter, like this:

data_file = models.FileField(upload_to=content_path)

Where content_path can be a string or a function which returns a string.

Upvotes: 13

Related Questions