You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图无法自动下载SRT转录文件问题求助

Django转录完成后文件无法自动下载的问题

我的Django视图会处理文件转录并生成SRT格式的转录文本,按预期转录完成后应该自动下载文件,但现在没有任何反应。文件是通过transcribeSubmit视图上传的,处理并返回文件的是initiate_transcription视图,目前控制台只返回状态码200。


views.py代码

@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代码

const form = document.querySelector('form');
form.addEventListener('submit', function (event) {
    event.preventDefault();

    const formData = new FormData(form);
    const xhr = new XMLHttpRequest();

    xhr.open('POST', form.getAttribute('action'), true);
    xhr.onreadystatechange = function () {
        console.log("ready state: ", xhr.readyState);
        console.log("status: ", xhr.status);
    }
    xhr.responseType = 'blob';
    xhr.send(formData);
});

HTML代码

<form id="initiate-transcription-form" method="post" action="{% url 'initiate_transcription' %}" enctype="multipart/form-data">
                    {% csrf_token %}
                <div>
                    <label for="output-lang--select-summary"></label>
                    <select class="output-lang-select" id="output-lang--select-summary" name="audio_language">
                        <option value="detect">Detect language</option>
                        <option value="zh">Chinese</option>
                        <option value="en">English</option>
                        <option value="es">Spanish</option>
                        <option value="de">German</option>
                        <option value="jp">Japanese</option>
                        <option value="ko">Korean</option>
                        <option value="ru">Russian</option>
                        <option value="pt">Portugese</option>
                <!-- add more language options as needed -->
                    </select>
                </div> 
                <button id="transcribe-button" type="submit">Click to Transcribe
                        <svg class="download-transcript" width="18" height="18" viewBox="0 0 24 24">
                            <path d="M19,9h-4V3H9v6H5l7,7L19,9z M5,18v2h14v-2H5z" fill="white"/>
                        </svg>
                            
                    </button>   
                
    </form>

问题原因及解决办法

核心问题

浏览器不会自动处理AJAX请求返回的附件,你需要手动解析返回的Blob数据并触发下载动作。

修改JavaScript代码

替换原JS逻辑,添加下载触发处理:

const form = document.querySelector('form');
form.addEventListener('submit', function (event) {
    event.preventDefault();

    const formData = new FormData(form);
    const xhr = new XMLHttpRequest();

    xhr.open('POST', form.getAttribute('action'), true);
    xhr.responseType = 'blob';
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            // 创建Blob临时URL
            const blob = xhr.response;
            const url = window.URL.createObjectURL(blob);
            
            // 创建a标签触发下载
            const a = document.createElement('a');
            a.href = url;
            
            // 从响应头提取文件名
            const contentDisposition = xhr.getResponseHeader('Content-Disposition');
            let filename = 'transcript.srt';
            if (contentDisposition) {
                const matches = contentDisposition.match(/filename="?([^"]+)"?/);
                if (matches && matches[1]) {
                    filename = matches[1];
                }
            }
            a.download = filename;
            
            document.body.appendChild(a);
            a.click();
            
            // 清理资源
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        }
    };
    
    xhr.send(formData);
});

视图层优化建议

  1. 跨平台路径处理:原代码用split('\\')仅适配Windows,替换为os.path模块保证跨平台兼容:
    import os
    # ...
    transcript_path = os.path.join(os.path.dirname(file_path), transcript_name)
    
  2. 文件存在校验:在读取SRT文件前,添加文件存在判断,避免报错:
    if os.path.exists(transcript_path):
        with open(transcript_path, 'r') as f:
            file_data = f.read()
    else:
        # 处理文件未生成的情况,比如返回错误提示
        return HttpResponse("Transcript file not generated", status=500)
    
  3. 确认转录逻辑执行:检查transcribe_file函数是否正确生成了目标SRT文件,可添加日志或打印路径验证。

内容的提问来源于stack exchange,提问作者tthheemmaannii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:06:03