Python Django-如何从输入文件标签中读取文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Django-如何从输入文件标签中读取文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1586字,纯文字阅读大概需要3分钟。
内容图文
![Python Django-如何从输入文件标签中读取文件?](/upload/InfoBanner/zyjiaocheng/734/898ef38cdeb64c90b284763ef06e5562.jpg)
我不希望文件保存在我的服务器上,我只想在下一页中读取和打印文件.现在我有这个.
(index.html)
<form name="fileUpload" method="post">
<input type="file" />
<input type="submit" value="Submit" />
</form>
而我正试图做这样的事情 –
def upload_file(request):
if request.method == "POST":
upload = request.POST.get('fileUpload').read()
return render(request, 'directory/return.html', {'output': upload})
else:
return render(request, 'directory/index.html')
但显然这是行不通的.我希望它适用于文本文件和csv文件.
谢谢.
解决方法:
首先,表单中缺少一些您必须添加的内容.
要使用表单上传文件,您需要在< form>中将enctype定义为“multipart / form-data”.元件.此外,文件输入元素中应包含name属性
的index.html
<form enctype="multipart/form-data" action="/my/url/" method="post"> # define the enctype
<input type="file" name="my_uploaded_file"/> # define a 'name' attribute
<input type="submit" value="Submit" />
</form>
然后,在您的视图中,您可以使用request.FILES字典访问上载的文件.根据要求.FILES文档:
Each key in
FILES
is the name from the<input type="file" name="" />
.
Each value inFILES
is anUploadedFile
.
您可以使用request.FILES字典中的my_uploaded_file键访问上载的文件.
views.py
def upload_file(request):
if request.method == "POST":
my_uploaded_file = request.FILES['my_uploaded_file'].read() # get the uploaded file
# do something with the file
# and return the result
else:
return render(request, 'directory/index.html')
注意:
request.FILES
will only contain data if the request method wasPOST
and the<form>
that posted the request has the attribute
enctype="multipart/form-data"
. Otherwise,request.FILES
will be empty.
内容总结
以上是互联网集市为您收集整理的Python Django-如何从输入文件标签中读取文件?全部内容,希望文章能够帮你解决Python Django-如何从输入文件标签中读取文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。