python - 如何通过 Django 查看上传的文本文件?

我现在正在制作网络应用程序。此应用程序获取具有未组织数据的文本文件并对其进行组织。我现在在 Python3 中使用 Django。

我已经在模板中制作了表单数据。

  • 模板

>    <form action="/practice/kakao_reader/" method="post"enctype="multipart/form-data">{% csrf_token %}
>        File:
>        <input type="file" name="file"/>
>        <input type="submit" value="UPLOAD" />
>     </form>

但是我很难通过VIEW获取上传的文件。 我试过的第一个代码是

  • 查看.py

def kakao_reader(request):

f = codecs.open(request.FILES['file'], encoding = 'utf-8')

data = f.read()

我收到无效文件:InMemoryUploadedFile:这个错误。

具体错误是

Environment:

Request Method: POST Request URL: http://localhost:8000/practice/kakao_reader/

Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'elections', 'practice'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)

File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)

File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Django\mysite\practice\views.py" in kakao_json 43. f = codecs.open(request.FILES['file'], encoding = 'utf-8')

File "C:\Python35\Lib\codecs.py" in open 895. file = builtins.open(filename, mode, buffering)

Exception Type: TypeError at /practice/kakao_reader/ Exception Value: invalid file:

我该如何解决?谢谢。

最佳答案

request.FILES['file'] 已经是文件处理程序,因此您不必打开它。只需使用 request.FILES['file'].read()

https://stackoverflow.com/questions/39436612/

相关文章:

regex - 如何在不使用 json 库和 json 解析器的情况下解析 json 文件

scala - Akka 流 : Can not write to file sink

php - 使用 openssl_encrypt 代替 Mcrypt 进行 3DES-ECB 加密

apache-spark - 如何在范围内划分数字列并为 apache spark 中的每个范围分配

fortran - IF 和 ENDIF 之前的 # 是什么意思

json - 使用 JOLT 转换重命名嵌套数组中的字段

html - 隐藏来自 HTML 电子邮件的预览文本的内容

python - 如何为使用 gmail 发送的电子邮件添加主题?

SQL - 如何在 UNION 查询中排序

angular - 在 Angular 2 模板中使用普通 POST 表单会导致 : "Templa