我不想将文件保存在我的服务器上,我只想在下一页中读取并打印该文件。现在我有这个。
(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 文件。
谢谢。
首先,您的表格中缺少一些内容,您必须添加这些内容。
要使用表单上传文件,您需要定义enctype
as "multipart/form-data"
在里面<form>
元素。另外,文件输入元素应具有name
属性在里面
索引.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 https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpRequest.FILES字典。按照request.FILES
docs:
每个键输入FILES
是来自的名字<input type="file" name="" />
。
中的每个值FILES
is an UploadedFile
.
您可以使用以下方式访问上传的文件my_uploaded_file
键入request.FILES
字典。
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')
Note:
request.FILES
仅当请求方法为时才包含数据POST
和<form>
发布请求的属性enctype="multipart/form-data"
。否则,request.FILES
将是空的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)