Reputation: 2470
The code below works very well by uploading files to server.
please how do I validate and secure the files upload by checking the files Size (Eg. 2mb), file extension name, Files Mimetype and other checking to ensure that only image like .jpg,.gif,.png are uploaded and not virus.
model.py
from django.db import models
# Create your models here.
class File(models.Model):
file = models.FileField()
def __str__(self):
return self.file.name
View.py
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from .models import File
import os, datetime
from .forms import uploadForm
# Create your views here.
def index(request):
if request.method == 'POST' and request.FILES:
form = uploadForm(request.POST,request.FILES)
if form.is_valid():
file = request.FILES['file']
# process the data in form.cleaned_data as required
file_object = form.cleaned_data['file']
extension = os.path.splitext(file_object.name)[1]
rename = datetime.datetime.now().strftime("%Y_%m_%d %H_%M_%S") + extension
fss = FileSystemStorage()
filename = fss.save(rename, file_object)
file = File(file=rename)
file.save()
upload_file_path = fss.path(filename)
return render(request, 'file/index.html', {
'upload_file_path': upload_file_path})
print('uploaded')
else:
print("Not Valid")
else:
return render(request, 'file/index.html')
forms.py
from django import forms
class uploadForm(forms.Form):
#file = forms.CharField()
file = forms.FileField()
Upvotes: 3
Views: 3810
Reputation: 812
You cannot trust any of the file's metadata to determine the content. I can send you a file with a .txt
extension that could be executed on your machine.
The only relatively safe way to handle this is by inspecting the content. This is not simple, so you should use one of the existing third-party libraries like python-magic.
Even then, there are ways to fool this, wrapping content in the comment fields of other content, etc..
You should never execute user submitted content.
Upvotes: 8