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.

Community
  • 1
  • 1
Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75

1 Answers1

1

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

fout = open(filedir +'/'+ filename, 'wb')
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks it worked.. will you be able to explain further? – Marlon Abeykoon Apr 06 '16 at 15:05
  • 1
    @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 http://stackoverflow.com/questions/2665866/what-is-the-wb-mean-in-this-code-using-python. Hope that helps. – alecxe Apr 06 '16 at 15:45