Open In App

Django – Upload files with FileSystemStorage

Django ships with the FileSystemStorage class that helps to store files locally so that these files can be served as media in development. In this article, we will see how to implement a file upload system using FileSystemStorage API to store the files locally. 
Note:This method should only be used in development and not in production. 

How to Upload Files with FileSystemStorage?




<form method = 'POST' class="col s12" enctype="multipart/form-data">
 
        {% csrf_token %}
 
        {{new_form.as_p}}
 
    <!--Below is our main file upload input -->
        <input type = "file" name = 'document'>
        <p><button type = "submit" class = "waves-effect waves-light btn" style = "background-color: teal">Publish</button></p>
</form>

from django.core.files.storage import FileSystemStorage




if request.method == "POST":
    # if the post request has a file under the input name 'document', then save the file.
    request_file = request.FILES['document'] if 'document' in request.FILES else None
    if request_file:
            # save attached file
 
            # create a new instance of FileSystemStorage
            fs = FileSystemStorage()
            file = fs.save(request_file.name, request_file)
            # the fileurl variable now contains the url to the file. This can be used to serve the file when needed.
            fileurl = fs.url(file)
 
return render(request, "template.html")




MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # media directory in the root directory
MEDIA_URL = '/media/'

from django.conf.urls.static import static
from django.conf import settings




# only in development
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Output – 
The frontend should look something like this 



As mentioned earlier, this method should only be used to serve media in development and not in production. You might want to use something like nginx in production.




Article Tags :