如何从Django视图接收文件作为对Ajax请求的响应

时间:2018-06-20 13:37:53

标签: python ajax django file-handling

我正在使用Python(3.6)和Django(1.11)开发一个项目,其中已经实现了Django视图,该视图通过ajax请求进行调用,该视图将返回音频mp3文件。如何获得此文件响应并发送到浏览器(应下载到用户)?

这是我的代码: views.py:

       if form.is_valid():
            obj = form
            obj.textFile = form.cleaned_data['textFile']
            obj.gender = form.cleaned_data['gender']
            obj.pitch = form.cleaned_data['pitch']
            obj.speed = form.cleaned_data['speed']
            obj.voice_type = form.cleaned_data['voice_type']
            obj.save()
            text_path = os.path.join(settings.MEDIA_ROOT, 'texts/', obj.textFile.name)
            text = text_path
            txt = Path(text).read_text(encoding='cp1252')
            fileName = obj.textFile.name[:-4]
            print('File Name is: {}'.format(fileName))
            input_text = {'text': txt}
            voice = {
                'language_code': 'en-US',
                'ssml_gender': obj.gender,
            }
            audio_config = {
                'audio_encoding': texttospeech_v1beta1.enums.AudioEncoding.MP3,
                'pitch': float(obj.pitch),
                'speaking_rate': float(obj.speed),
            }
            client = texttospeech_v1beta1.TextToSpeechClient(credentials=credentials)
            response = client.synthesize_speech(input_=input_text,
                                                voice=voice,
                                                audio_config=audio_config)
            with open('media/audios/' + str(fileName) + '.mp3', 'wb') as out:
                out.write(response.audio_content)
                print('Audio content written to file "output.mp3"')

            # dict_response = dict(response)
            response_file = FileResponse('media/audios/output.mp3', content_type='mp3')
            response_file['Content-Disposition'] = 'attachment; filename="output.mp3"'
            return HttpResponse(response_file)
        return HttpResponse('Get post request along with files', status=200)

Ajax请求代码:

 $(document).on('submit', '#fileForm', function (e) {
    e.preventDefault();
    var data = new FormData($('#fileForm').get(0));
    $.ajax({
        type: 'POST',
        url: '{% url 'home' %}',
        data: data,
        processData: false,
        contentType: false,
        success: function () {
            console.log('Succcess');
            $('#success').attr('hidden', false);
        }
    });
});

请帮帮我!

谢谢!

0 个答案:

没有答案