Загрузить Excel, используя web.py
Я попробовал следующий код, слегка изменив пример в документации
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.
Но это работает только для документов CSV и TXT. Для Excel/pdf и т. Д. Файл создается, но не может быть открыт (поврежден). Что я должен сделать, чтобы справиться с этим сценарием?
Я видел это, но речь идет о печати контента, который не касается моего вопроса.
1 ответ
Решение
Вам нужно использовать wb
(бинарный) режим при открытии файла:
fout = open(filedir +'/'+ filename, 'wb')