gpt4 book ai didi

python - 如何在 Django 中上传文件并显示进度条?

转载 作者:太空狗 更新时间:2023-10-30 01:38:50 33 4
gpt4 key购买 nike

我编写了如下代码在 Django 中上传文件:

def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return render_to_response('uploadsuccess.html')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})


def handle_uploaded_file(f):
filename = "/media/Data/static/Data/" + f.name
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()

代码对我来说工作正常。但是,我不知道应该如何修改此代码以在客户端显示进度条。

我的 html 页面如下所示:

{% extends "index_base.html" %}

{% block content %}
<script src="/media/js/functions.js" type="text/javascript"></script>
<script src="/media/js/jquery.js" type="text/javascript">
</script>
<div id="main_container">

{% include "includes/nav.html" %}

<!------- Main Contents ---------->
<div id="contents_holder">
<div id="contents">
<div id="c_banner">
<span class="main_title">Upload File</span>
</div>
<div id="setting">
<form name="post" action="/upload.psp/" method="post" enctype="multipart/form-data">
<h2>Upload File</h2></br>
<p>{{ form.file.label_tag }}&nbsp;&nbsp;{{ form.file }}</p></br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="Upload" name="uploadButton" />
&nbsp;&nbsp;<input type="button" value="Cancel" name="cancelUploadButton" onclick ="cancelUploadClicked()"/>
<input type="hidden" value="title" name="title" id="title" />
</form>
</div>

</div>
</div>
</div>

<!------- Main Contents Finished ---------->
{% endblock %}

谁能帮我把上传进度条和这段代码整合起来?

提前致谢。

最佳答案

我认为您必须使用 Ajax 发送异步请求。

这里也讨论了这个话题:File upload progress bar with jquery在这里:How can I upload files asynchronously?

关于python - 如何在 Django 中上传文件并显示进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073903/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com