def ingest_form(request): """Display or process the file ingest form. On GET, display the form. On valid POST, reposit the submitted file in a new digital object. """ if request.method == 'POST': form = IngestForm(request.POST, request.FILES) if form.is_valid(): # use mime magic to determine type of object to create m = magic.Magic(mime=True) mimetype = m.from_file(request.FILES['file'].temporary_file_path()) objtype = object_type_from_mimetype(mimetype) # initialize a connection to the repository and create a new object repo = Repository(request=request) fobj = repo.get_object(type=objtype) # set file mimetype in dc:format # TODO: file checksum? st = (fobj.uriref, relsext.isMemberOfCollection, URIRef(form.cleaned_data['collection'])) fobj.rels_ext.content.add(st) fobj.master.content = request.FILES['file'] fobj.master.mimetype = mimetype # pre-populate the object label and dc:title with the uploaded filename fobj.label = fobj.dc.content.title = request.FILES['file'].name # also use the original filename as the file datastream label fobj.master.label = request.FILES['file'].name fobj.save('ingesting user content') messages.success(request, 'Successfully ingested <a href="%s"><b>%s</b></a>' % \ (reverse('file:view', args=[fobj.pid]), fobj.pid)) return HttpResponseSeeOtherRedirect(reverse('site-index')) else: initial_data = {} # if collection is specified in url parameters, pre-select the # requested collection on the form via initial data if 'collection' in request.GET: initial_data['collection'] = request.GET['collection'] form = IngestForm(initial=initial_data) return render(request, 'file/ingest.html', {'form': form})
def test_object_type_from_mimetype(self): self.assertEqual(ImageObject, object_type_from_mimetype('image/jpeg')) self.assertEqual(ImageObject, object_type_from_mimetype('image/gif')) self.assertEqual(FileObject, object_type_from_mimetype('image/unsupported-img')) self.assertEqual(FileObject, object_type_from_mimetype('text/plain'))