dizwe
dizwe

Reputation: 81

How can I get uploaded text file in view through Django?

I'm now making web app. This app gets text file having not-organized data and organize it. I'm now using Django in Python3.

I already made form data in templates.

>    <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>

But I have difficulty in getting uploaded file through VIEW. The first code that I've tried was

def kakao_reader(request):

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

data = f.read()

And I get invalid file: InMemoryUploadedFile: this error.

The specific Error is

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:

How can I fix it? thank you.

Upvotes: 3

Views: 5915

Answers (1)

Domen Blenkuš
Domen Blenkuš

Reputation: 2242

request.FILES['file'] is already a file handler, so you don't have to open it. Just use request.FILES['file'].read().

Upvotes: 11

Related Questions