예제 #1
0
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})
예제 #2
0
 def test_image_conversion_for_image_file(self):
     """
     Tests converting the 'self.image_file_path' to PNG.
     """
     # Given
     with open(self.image_file_path) as f:
         # When
         result = convert_image_to_jpeg(f)
         img = Image.open(result)
         # Then
         self.assertEqual(JpegImageFile.format, img.format)
     self.assertEqual(self._convert_file(self.image_file_path, JpegImageFile.format).getvalue(),
                      result.getvalue())
예제 #3
0
 def test_upload_post_with_image_file(self):
     """
     Tests POSTing a form which contains a file where the file is an image.
     """
     # Given
     c = Client()
     # When
     with open(self.image_file_path) as fp:
         response = c.post('/', {'file': fp})
         converted_image = convert_image_to_jpeg(fp)
     # Then
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}.jpg'.format(self.image_file_name))
     self.assertEqual(response.content, converted_image.getvalue())