【问题标题】:Upload Excel using web.py使用 web.py 上传 Excel
【发布时间】:2016-03-30 13:27:29
【问题描述】:

我已经通过稍微修改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.

但这仅适用于 csv 和 txt 文档。对于 Excel/pdf 等文件已创建但无法打开(损坏)。我应该怎么做才能处理这种情况?

我看到了this,但它是关于打印与我无关的内容。

【问题讨论】:

    标签: python excel file-upload web.py


    【解决方案1】:

    打开文件时需要使用wb(二进制)模式:

    fout = open(filedir +'/'+ filename, 'wb')
    

    【讨论】:

    • 谢谢它的工作..你能进一步解释吗?
    • @MarlonAbeykoon 如果您要在 Windows 上使用 w,则在写入上传的内容时会收到损坏的文件,因为行尾字符的处理方式不同,请参阅 stackoverflow.com/questions/2665866/…。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2011-10-20
    • 2015-05-10
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多