def upload_and_convert_image_file(request): """ The main view which accepts a file via an 'ImageConverterForm', converts it to a JPEG file and returns it ready for download as an attachment. """ if request.method == 'POST': form = ImageConverterForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES['file'] context = { 'file': f, } try: converted_img = convert_image_to_jpeg(f) name = get_filename_without_extension(f.name) response = HttpResponse(converted_img.getvalue(), content_type='image/jpeg') response['Content-Disposition'] = 'attachment; filename={0}.jpg'.format(name) return response except IOError: return render(request,'unsupported_image_file_error.html', context) except Exception as e: return render(request,'generic_error.html', context) else: form = ImageConverterForm() return render(request, 'upload.html', {'form': form})
def test_empty_filename(self): """ Tests an empty file name. """ # Given expected_name = 'file' # When name = get_filename_without_extension('') # Then self.assertEqual(expected_name, name)
def test_filename_without_extension(self): """ Tests random file names that lack an extension. """ for _ in xrange(100): # Given expected_filename = ''.join([choice(letters) for _ in xrange(8)]) # When name = get_filename_without_extension(expected_filename) # Then self.assertEqual(expected_filename, name)
def test_standard_filename(self): """ Tests random file names which are made up of a name without any dots and a single extension; name and extension are separated by a dot. """ for _ in xrange(100): # Given expected_name = ''.join([choice(letters) for _ in xrange(8)]) extension = ''.join([choice(letters) for _ in xrange(3)]) filename = '{0}.{1}'.format(expected_name, extension) # When name = get_filename_without_extension(filename) # Then self.assertEqual(expected_name, name)
def test_multiple_extensions(self): """ Tests random file names with multiple extensions. """ for _ in xrange(100): # Given filename = ''.join([choice(letters) for _ in xrange(8)]) for _ in xrange(10): filename += '.'.join([choice(letters) for _ in xrange(3)]) # When name = get_filename_without_extension(filename) # Then expected_name, extension = filename.rsplit('.', 1) self.assertEqual(expected_name, name)