Python django.http.StreamingHttpResponse() Examples

The following are 30 code examples for showing how to use django.http.StreamingHttpResponse(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: seqr   Author: macarthur-lab   File: igv_api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _stream_file(request, path):
    # based on https://gist.github.com/dcwatson/cb5d8157a8fa5a4a046e
    content_type = 'application/octet-stream'
    range_header = request.META.get('HTTP_RANGE', None)
    if range_header:
        range_match = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I).match(range_header)
        first_byte, last_byte = range_match.groups()
        first_byte = int(first_byte) if first_byte else 0
        last_byte = int(last_byte)
        length = last_byte - first_byte + 1
        resp = StreamingHttpResponse(
            file_iter(path, byte_range=(first_byte, last_byte)), status=206, content_type=content_type)
        resp['Content-Length'] = str(length)
        resp['Content-Range'] = 'bytes %s-%s' % (first_byte, last_byte)
    else:
        resp = StreamingHttpResponse(file_iter(path), content_type=content_type)
    resp['Accept-Ranges'] = 'bytes'
    return resp 
Example 2
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
    answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id)

    real_secret = answer.answer['data'].get('secret', '?')
    if real_secret != '?' and secret == real_secret:
        return _return_submitted_file(answer.answer['data'], answer.file.open('rb'))

    else:
        # It's not the current submission, but an instructor looking at history might be trying to find an old one...
        submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member)
        for qs in submissions:
            for answer_config in qs.config['answers']:
                version_id, answer_id, a = answer_config
                if not isinstance(a['data'], dict):
                    continue
                real_secret = a['data'].get('secret', '?')
                if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret:
                    # aha! Temporarily replace answer.file with the old version (without saving) so we can return it
                    answer.file = a['filepath']
                    return _return_submitted_file(a['data'], answer.file.open('rb'))

    raise Http404() 
Example 3
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def view_attachment(request, userid, event_slug, attach_slug):
    person, member_units = _get_faculty_or_404(request.units, userid)
    event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
    viewer = get_object_or_404(Person, userid=request.user.username)

    attachment = get_object_or_404(event.attachments.all(), slug=attach_slug)

    handler = event.get_handler()
    if not handler.can_view(viewer):
        raise PermissionDenied("Not allowed to view this attachment")

    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 4
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download_attachment(request, userid, event_slug, attach_slug):
    person, member_units = _get_faculty_or_404(request.units, userid)
    event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
    viewer = get_object_or_404(Person, userid=request.user.username)

    attachment = get_object_or_404(event.attachments.all(), slug=attach_slug)

    handler = event.get_handler()
    if not handler.can_view(viewer):
        raise PermissionDenied("Not allowed to download this attachment")

    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 5
Project: tom_base   Author: TOMToolkit   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        """
        Returns a response containing the exported CSV of selected targets.

        :param context: Context object for this view
        :type context: dict

        :returns: response class with CSV
        :rtype: StreamingHttpResponse
        """
        qs = context['filter'].qs.values()
        file_buffer = export_targets(qs)
        file_buffer.seek(0)  # goto the beginning of the buffer
        response = StreamingHttpResponse(file_buffer, content_type="text/csv")
        filename = "targets-{}.csv".format(slugify(datetime.utcnow()))
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response 
Example 6
Project: BioQueue   Author: liyao001   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def export_protocol(request):
    if request.method == 'GET':
        if 'id' in request.GET:
            pname, protocol_text = build_plain_protocol(request, request.GET['id'])
            if protocol_text == 1:
                return error('Cannot find the protocol.')
            elif protocol_text == 2:
                return error('You are not owner of the protocol.')
            else:
                from django.http import StreamingHttpResponse
                response = StreamingHttpResponse(protocol_text)
                response['Content-Type'] = 'application/octet-stream'
                response['Content-Disposition'] = 'attachment;filename="{0}"'.format(str(pname + '.txt'))
                return response
        else:
            return error('Unknown parameter.')
    else:
        return error('Method error.') 
Example 7
Project: InvenTree   Author: inventree   File: helpers.py    License: MIT License 6 votes vote down vote up
def DownloadFile(data, filename, content_type='application/text'):
    """ Create a dynamic file for the user to download.
    
    Args:
        data: Raw file data (string or bytes)
        filename: Filename for the file download
        content_type: Content type for the download

    Return:
        A StreamingHttpResponse object wrapping the supplied data
    """

    filename = WrapWithQuotes(filename)

    if type(data) == str:
        wrapper = FileWrapper(io.StringIO(data))
    else:
        wrapper = FileWrapper(io.BytesIO(data))

    response = StreamingHttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = len(data)
    response['Content-Disposition'] = 'attachment; filename={f}'.format(f=filename)

    return response 
Example 8
Project: janeway   Author: BirkbeckCTP   File: files.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def serve_file(request, file_to_serve, article, public=False, hide_name=False):
    """Serve a file to the user using a StreamingHttpResponse.

    :param request: the active request
    :param file_to_serve: the file object to retrieve and serve
    :param article: the associated article
    :param public: boolean
    :param hide_name: boolean
    :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
    permission error
    """
    path_parts = ('articles', article.pk)
    return serve_any_file(
        request,
        file_to_serve,
        public,
        hide_name=hide_name,
        path_parts=path_parts
    ) 
Example 9
Project: janeway   Author: BirkbeckCTP   File: files.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def serve_journal_cover(request, file_to_serve):
    """Serve a file to the user using a StreamingHttpResponse.

    :param request: the active request
    :param file_to_serve: the file object to retrieve and serve
    :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
    permission error
    """

    file_path = os.path.join(settings.BASE_DIR, 'files', 'journals', str(request.journal.id),
                             str(file_to_serve.uuid_filename))

    try:
        response = serve_file_to_browser(file_path, file_to_serve)
        return response
    except IOError:
        messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 
Example 10
Project: janeway   Author: BirkbeckCTP   File: files.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def serve_press_cover(request, file_to_serve):
    """Serve a file to the user using a StreamingHttpResponse.

    :param request: the active request
    :param file_to_serve: the file to serve
    :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
    permission error
    """

    file_path = os.path.join(settings.BASE_DIR, 'files', 'press', str(file_to_serve.uuid_filename))

    try:
        response = serve_file_to_browser(file_path, file_to_serve)
        return response
    except IOError:
        messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 
Example 11
Project: davvy   Author: unbit   File: base.py    License: MIT License 6 votes vote down vote up
def get(self, request, user, resource_name):
        resource = self.get_resource(request, user, resource_name)
        if resource.collection:
            return HttpResponseForbidden()

        response = StreamingHttpResponse(
            self.storage.retrieve(
                self, request, resource
            ),
            content_type=resource.content_type
        )

        response['Content-Length'] = resource.size
        response[
            'Content-Disposition'] = "attachment; filename=%s" % resource.name
        return response 
Example 12
Project: sfm-ui   Author: gwu-libraries   File: views.py    License: MIT License 6 votes vote down vote up
def export_file(request, pk, file_name):
    """
    Allows authorized user to export a file.

    Adapted from https://github.com/ASKBOT/django-directory
    """
    export = get_object_or_404(Export, pk=pk)
    if (request.user == export.user) or request.user.is_superuser:
        filepath = os.path.join(export.path, file_name)
        log.debug("Exporting %s", filepath)
        if os.path.exists(filepath):
            response = StreamingHttpResponse()
            response['Content-Disposition'] = 'attachment; filename=%s' % file_name
            response['Content-Type'] = 'application/octet-stream'
            file_obj = open(filepath, 'rb')
            response.streaming_content = _read_file_chunkwise(file_obj)
            return response
        else:
            raise Http404
    else:
        raise PermissionDenied 
Example 13
Project: django-seeker   Author: imsweb   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def export(self):
        """
        A helper method called when ``_export`` is present in ``request.GET``. Returns a ``StreamingHttpResponse``
        that yields CSV data for all matching results.
        """
        keywords = self.get_keywords()
        facets = self.get_facet_data()
        search = self.get_search(keywords, facets, aggregate=False)
        columns = self.get_columns()

        def csv_escape(value):
            if isinstance(value, (list, tuple)):
                value = '; '.join(force_text(v) for v in value)
            return '"%s"' % force_text(value).replace('"', '""')

        def csv_generator():
            yield ','.join('"%s"' % c.label for c in columns if c.visible and c.export) + '\n'
            for result in search.scan():
                yield ','.join(csv_escape(c.export_value(result)) for c in columns if c.visible and c.export) + '\n'

        export_timestamp = ('_' + timezone.now().strftime('%m-%d-%Y_%H-%M-%S')) if self.export_timestamp else ''
        export_name = '%s%s.csv' % (self.export_name, export_timestamp)
        resp = StreamingHttpResponse(csv_generator(), content_type='text/csv; charset=utf-8')
        resp['Content-Disposition'] = 'attachment; filename=%s' % export_name
        return resp 
Example 14
Project: mooder   Author: phith0n   File: views.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        post = get_object_or_404(self.get_queryset(), pk=self.kwargs['pk'])
        if request.user.is_superuser or request.user.has_perm('archives.change_post') or post.author_id == request.user.id:
            pass
        elif post.visible == 'private' or post.visible == 'sell' and not post.buyers.filter(id=request.user.id).exists():
            raise Http404

        chunk_size = 8192
        response = StreamingHttpResponse(FileWrapper(open(post.attachment.path, 'rb'), chunk_size),
                                         content_type='application/octet-stream')
        response['Content-Length'] = post.attachment.size

        filename = post.attachment_filename if post.attachment_filename else 'attachment'
        response["Content-Disposition"] = \
            "attachment; " \
            "filenane={ascii_filename};" \
            "filename*=UTF-8''{utf_filename}".format(
                ascii_filename=quote(filename),
                utf_filename=quote(filename)
            )
        return response 
Example 15
Project: sal   Author: salopensource   File: csv.py    License: Apache License 2.0 6 votes vote down vote up
def get_csv_response(queryset: QuerySet,
                     fields: dict,
                     title: str) -> StreamingHttpResponse:
    writer = csv.writer(PassthroughIO())

    # Nest field names into an iterable of 1 so it can be chained.
    # Add in our two foreign key traversals by name.
    headers = [fields.keys()]
    data = (row_helper(item, fields) for item in queryset)
    # Chain the headers and the data into a single iterator.
    generator = (writer.writerow(row) for row in itertools.chain(headers, data))

    # Streaming responses require a generator; which is good, as it can
    # process machines one by one rather than shoving the entire output
    # into memory.
    response = StreamingHttpResponse(generator, content_type="text/csv")
    # If DEBUG_CSV  is enabled, just print output rather than download.
    if not server.utils.get_django_setting('DEBUG_CSV', False):
        response['Content-Disposition'] = 'attachment; filename="%s.csv"' % title
    return response 
Example 16
Project: texta   Author: texta-tk   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def export_matched_data(request):
    search_id = request.GET['search_id']

    inclusive_metaquery = json.loads(request.GET['inclusive_grammar'])

    ds = Datasets().activate_dataset(request.session)

    component_query = ElasticGrammarQuery(inclusive_metaquery, None).generate()

    es_m = ds.build_manager(ES_Manager)

    if search_id == '-1': # Full search
        es_m.combined_query = component_query
    else:
        saved_query = json.loads(Search.objects.get(pk=search_id).query)
        es_m.load_combined_query(saved_query)
        es_m.merge_combined_query_with_query_dict(component_query)

    inclusive_instructions = generate_instructions(inclusive_metaquery)

    response = StreamingHttpResponse(get_all_matched_rows(es_m.combined_query['main'], request, inclusive_instructions), content_type='text/csv')

    response['Content-Disposition'] = 'attachment; filename="%s"' % ('extracted.csv')

    return response 
Example 17
Project: texta   Author: texta-tk   File: export_pages.py    License: GNU General Public License v3.0 6 votes vote down vote up
def export_pages(request):

    es_params = request.session.get('export_args')
    if es_params is not None:
        if es_params['num_examples'] == '*':
            response = StreamingHttpResponse(get_all_rows(es_params, request), content_type='text/csv')
        else:
            response = StreamingHttpResponse(get_rows(es_params, request), content_type='text/csv')

        response['Content-Disposition'] = 'attachment; filename="%s"' % (es_params['filename'])

        return response

    logger = LogManager(__name__, 'SEARCH CORPUS')
    logger.set_context('user_name', request.user.username)
    logger.error('export pages failed, parameters empty')
    return HttpResponse() 
Example 18
Project: OMS   Author: ywzhou123   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def salt_file_download(request, file_name):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8') #解决中文字符默认使用ascii编码问题,不用管得示not find,reload后自然就有了
    def file_iterator(file, chunk_size=512):
        with open(file) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
        f.close()
    response = StreamingHttpResponse(file_iterator(file_name))
    #为了可以下载任意类型文件
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name)
    return response 
Example 19
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def download(self, request, *args, **kwargs):
        """
        Download the volume data.
        """
        volume = self.get_object()

        # Check whether project is corresponding to the user
        user = request.user
        if not check_member_in_project(volume.project, user):
            raise PermissionDenied(detail="User {} is not in project {}."
                .format(user.username, volume.project.name))

        logger.info("User {} download the data of volume {}-{}.".format(
            request.user.username, volume.project.name, volume.name))

        # Copy file to local first
        volume_dir = get_volume_direction_on_nfs(volume)
        filename = get_upload_volume_filename(volume, request.user)
        client = NFSLocalClient()
        client.tar_and_copy_to_local(volume_dir, filename)

        response = StreamingHttpResponse(big_file_iterator(filename))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(
            os.path.basename(filename))

        return response 
Example 20
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def view_attachment(request, ra_slug, attach_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, unit__in=request.units)
    attachment = get_object_or_404(appointment.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 21
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_attachment(request, ra_slug, attach_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, unit__in=request.units)
    attachment = get_object_or_404(appointment.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 22
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _return_submitted_file(answer_data, data):
    content_type = answer_data.get('content-type', 'application/octet-stream')
    charset = answer_data.get('charset', None)
    filename = answer_data.get('filename', None)

    resp = StreamingHttpResponse(streaming_content=data, content_type=content_type, charset=charset, status=200)
    if filename:
        resp['Content-Disposition'] = 'inline; filename="%s"' % (filename,)
    return resp


# This view is authorized by knowing the secret not by session, to allow automated downloads of submissions from JSON. 
Example 23
Project: coursys   Author: sfu-fas   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_student_zip(self):
        self.ensure_components()
        assert self.submissions

        multi = self.activity.multisubmit()

        if multi:
            self.get_all_components()
            compsub = self.all_components_and_submitted()
        else:
            self.get_most_recent_components()
            compsub = self.components_and_submitted()

        handle, filename = tempfile.mkstemp('.zip')
        os.close(handle)
        z = zipfile.ZipFile(filename, 'w')

        self._add_to_zip(z, self.activity, compsub, self.submissions[0].created_at,
                slug=self.submissions[0].file_slug(), multi=multi)

        z.close()

        file = open(filename, 'rb')
        response = StreamingHttpResponse(FileWrapper(file), content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="%s_%s.zip"' % (
                self.submissions[0].file_slug(), self.activity.slug)
        try:
            os.remove(filename)
        except OSError:
            pass

        return response 
Example 24
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def view_attachment(request, visa_id, attach_slug):
    visa = get_object_or_404(Visa, pk=visa_id)
    attachment = get_object_or_404(visa.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 25
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_attachment(request, visa_id, attach_slug):
    visa = get_object_or_404(Visa, pk=visa_id)
    attachment = get_object_or_404(visa.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 26
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def view_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 27
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 28
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _view_event_attachment(event):
    attachment = event.eventattachment
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 29
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_attachment(request, asset_id, attach_slug):
    asset = get_object_or_404(Asset, pk=asset_id, unit__in=request.units)
    attachment = get_object_or_404(asset.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp 
Example 30
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def view_position_attachment(request, position_id, attach_slug):
    position = get_object_or_404(Position, pk=position_id)
    attachment = get_object_or_404(position.attachments.all(), slug=attach_slug)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp