Ответ двоичных данных для загрузки - PullRequest
1 голос
/ 17 апреля 2020

Я пытаюсь ввести файл из поля ввода, временно сохранить его на диск и ответить с повторной загрузкой того же файла.

Для того, чтобы сделать это, я прочитал, что мне нужно ответить браузеру с content-type : application/octet-stream и content-disposition: attachment; "filename=myfile.extension".

Я могу хранить и слушать мои музыкальные произведения c файл в папке / tmp, так что я знаю, что его входная часть работает.

Это мой код в Pyramid:

@view_config(route_name='process')
def process_file(request):
    input_file = request.POST['file'].file
    input_file.seek(0)
    file_path = os.path.join('/tmp', '%s.mp3' % uuid.uuid4())
    with open(file_path, 'wb') as output_file:
        shutil.copyfileobj(input_file, output_file)
    print(f"Wrote: {file_path}")
    filename = file_path.split('/')[-1]
    print(filename)
    f = open(file_path, 'rb')
    return Response(body_file=f, charset='UTF-8', content_type='application/octet-stream', content_disposition=f'attachment; "filename={filename}"')

Это мои заголовки ответа: Response headers

И это мое тело ответа: Response body

Однако Chrome / Firefox не запускает загрузку моего двоичного файла. Что я делаю не так?

ОБНОВЛЕНИЕ

Я также безуспешно пытался с FileResponse из Пирамиды, я все еще не получаю всплывающее окно загрузки.

@view_config(route_name='process')
def process_file(request):
    input_file = request.POST['file'].file
    input_file.seek(0)
    file_path = os.path.join('/tmp', '%s.mp3' % uuid.uuid4())
    with open(file_path, 'wb') as output_file:
        shutil.copyfileobj(input_file, output_file)
    print(f"Wrote: {file_path}")
    return FileResponse(file_path, request=request)

1 Ответ

1 голос
/ 17 апреля 2020

Видимо, я думал, как это сделать неправильно. Мне нужно вернуть Response('OK'), когда я загружаю файл через /process и сделать еще один запрос на возврат объекта FileResponse, построение другой конечной точки /download и возвращение этого объекта fileresponse исправило эту проблему.

Пример:

@view_config(route_name='process')
def process_file(request):
    input_file = request.POST['file'].file
    db = request.POST['volume']
    input_file.seek(0)
    filename = '%s.mp3' % uuid.uuid4()
    file_path = os.path.join('/tmp', filename)
    with open(file_path, 'wb') as output_file:
        shutil.copyfileobj(input_file, output_file)
    if boost_track(file_path, filename, db):
        return Response(json_body={'filename': filename})

@view_config(route_name='download')
def download_file(request):
    filename = request.GET['filename']
    file_path = os.path.join('/tmp', filename)
    f = open(file_path, 'rb')
    return Response(body_file=f, charset='UTF-8', content_type='application/download', content_disposition=f'attachment; filename="{filename}"')
...