id="upload" type="file" name="file"/>! <input type="text" name="name"/>! <input type="text" name="website"/>! </form>! <a id="publishButton">Publish</div> WebDirectory/templates/WebDirectory/index.html this form handles multiple formats of data the URL to submit the form uploading files must be done through a POST request
path image/png path image/jpg The image path and the mime type are stored in the database POST add/ uploads The image is stored in the upload directory Image
path to the directory that will hold user-uploaded files.! # Example: "/home/media/media.lawrence.com/media/"! MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/') tsans/settings.py
models.CharField(max_length=200)! webpage = models.URLField(max_length=200) ! class Image(models.Model):! ! entry = models.ForeignKey(Entry, unique=True)! image = models.ImageField(upload_to='WebDirectory')! mimeType = models.CharField(max_length=20) WebDirectory/models.py where to store uploaded files use FileField for generic files We need to record the MIME type (see serving uploaded file) entry foreign key
@csrf_exempt! def add(request):! e = Entry(name = request.POST['name'],\! webpage = request.POST['website'])! e.save() ! i = Image(entry = e,\! image = request.FILES['file'],\! mimeType=request.FILES['file'].content_type)! i.save() ! return HttpResponseRedirect(reverse('index'))! WebDirectory/views.py get the file from the HTTP request Not secure but we will talk about security later get the MIME type
to control (controller) the file - getImage Reference the image using an identifier • automatically generated hash code • or database entry id (primary key in the database)
uploads Retrieve the image from the upload directory (this is done automatically by Django) Database img mime path image/png path image/jpg Get the image path and mime type from the database based on its id Return a HTTP response of the corresponding mime type Image
return HttpResponse(i.image.read(), content_type=i.mimeType)! ! def index(request):! ! image_list = Image.objects.all()! return render(request,’WebDirectory/index.html’,\ {'image_list': image_list}) WebDirectory/views.py get the file from the database return an HTTP response of the corresponding MIME type