2

I have tried the following code by slightly modifying the example in documentation

class Upload():
  def POST(self):
    web.header('enctype','multipart/form-data')
    print strftime("%Y-%m-%d %H:%M:%S", gmtime())
    x = web.input(file={})
    filedir = '/DiginUploads' # change this to the directory you want to store the file in.
    if 'file' in x: # to check if the file-object is created
        filepath=x.file.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
        filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
        fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
        fout.write(x.file.file.read()) # writes the uploaded file to the newly created file.
        fout.close() # closes the file, upload complete.

But this works only for csv and txt documents. For Excel/pdf etc file gets created but it can't be opened (corrupted). What should I do to handle this scenario?

I saw this but it is about printing the content which does not address my matter.

1 Answer 1

1
+50

You need to use wb (binary) mode when opening the file:

fout = open(filedir +'/'+ filename, 'wb')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked.. will you be able to explain further?
@MarlonAbeykoon if you would use the w, on windows, you would get corrupted files when writing the uploaded content since the end-of-line characters are handled differently, see stackoverflow.com/questions/2665866/…. Hope that helps.

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.