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()
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)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With