为什么文件下载在我的 Django 视图中不起作用?

Why is file download not working in my Django view?

提问人:tthheemmaannii 提问时间:10/10/2023 最后编辑:tthheemmaannii 更新时间:10/11/2023 访问量:32

问:

我的 Django 应用程序中的视图功能旨在转录文件并生成 .srt 格式的字幕文件。然后,它会识别脚本文件,并应自动下载它。但是,目前不会发生自动下载。文件是在使用视图的其他页面上提交的,而视图负责处理和返回文件。当我检查它返回的文件类型时,我怀疑它应该返回(尽管我认为这仅适用于二进制文件),就像它在我的代码使用的类似版本中一样,但我不确定要更改什么。这是我 views.py:transcribeSubmitinitiate_transcriptionfile_datastrbytes

@csrf_protect
def transcribeSubmit(request):
    
    if request.method == 'POST':
        
        
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            

            uploaded_file = request.FILES['file']
            fs = FileSystemStorage()
            filename = fs.save(uploaded_file.name, uploaded_file)
            request.session['uploaded_file_name'] = filename
            request.session['uploaded_file_path'] = fs.path(filename)
            
            
            #transcribe_file(uploaded_file)
            #return redirect(reverse('proofreadFile'))
            return render(request, 'transcribe/transcribe-complete.html', {"form": form})
        else:
            
    else:
        form = UploadFileForm()

        
        
    return render(request, 'transcribe/transcribe.html', {"form": form})

@csrf_protect
def initiate_transcription(request):
    
    if request.method == 'POST':
        
        
        # get the file's name and path from the session
        file_name = request.session.get('uploaded_file_name')
        file_path = request.session.get('uploaded_file_path')
        if file_name and file_path:
            with open(file_path, 'rb') as f:
                path_string = f.name
                transcribe_file(path_string)
            
            file_extension = ('.' + (str(file_name).split('.')[-1]))
            transcript_name = file_name.replace(file_extension, '.srt')
            
            transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name)
                
            file_location = transcript_path
            with open(file_location, 'r') as f:
                file_data = f.read()

            response = HttpResponse(file_data, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"'
            return response
            
        else:
            #complete

    return render(request, 'transcribe/transcribe-complete.html', {"form": form})

           
def transcribe_file(path):
#transcription logic

我在另一个有效的视图/页面上使用了类似的代码,但是当适应此页面时,它失败了。有什么想法吗?

JavaScript Python Django 文件

评论


答: 暂无答案