1

I want to handle the file uploaded by the guest, here is the views code:

def charset(request):                                   
    logging.info('charset')                             
    name = request.GET['name']                          
    file_path = os.path.join(settings.MEDIA_ROOT, name) 
    logging.info(file_path)                             
    logging.info(type(file_path))                       
    file1 = open(file_path.decode('utf8'), 'wb')        
    file1.write(b'test')                                
    file1.close()                                       
    return HttpResponse('success')                      

But an error occurred. The trace back is following:

UnicodeEncodeError at /upload/charset/
    'ascii' codec can't encode characters in position 27-28: ordinal not in range(128)

You can repeat the error by visiting: My Wrong Website

I'm using environment as these:

python 3.4.3  
django 1.9.3   
apache2 2.4.7

But when I run server using python3 manage.py runserver 0.0.0.0:8000. It works.
How can I fix this? Thank you for your attention. You can view the project code on the website github_of_my_django_tutorial.

2
  • 1
    The traceback on that link doesn't match the code you've posted above; there's no decode call. Commented May 27, 2016 at 9:17
  • Sorry, I have changed the code to this. I should use encode("utf8") to solve this. Commented May 30, 2016 at 1:09

1 Answer 1

1

You need to encode the filename to UTF-8 first:

name = name.encode("utf8")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.