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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…