【问题标题】:file uploaded with name in python django在 python django 中使用名称上传的文件
【发布时间】:2016-02-09 14:44:06
【问题描述】:

我正在使用此代码:

  def saveUploadedInventory(self, inventory_file,user_id): 
      with open('uploaded_inventory_sheet.csv','wb+') as destination:
          for chunk in inventory_file.chunks():
              destination.write(chunk)

      reader = csv.reader(open('uploaded_inventory_sheet.csv','rb'))

此名称的文件 Uploaded_inventory_sheet.csv 已成功上传

但我想将相同的文件上传到不同的目录,其实际名称来自客户端。

我尝试以下代码:

def saveUploadedInventory(self, inventory_file,user_id): 
    with open(''.join(inventory_file),'wb+') as destination:
        for chunk in inventory_file.chunks():
            destination.write(chunk)
    reader = csv.reader(open('inventory_file','rb'))

但它给出了以下错误:

异常类型:IOError

异常值:[Errno 36] 文件名太 长:'Se .. .. .

【问题讨论】:

  • ''.join(inventory_file) 的输出是什么?它似乎很长,而您真正想要的只是名称。
  • 我得到错误file name too long 然后文件的所有数据都打印在那里

标签: python django file-upload


【解决方案1】:

你想打开文件的名字,而不是加入它的内容:

def saveUploadedInventory(self, inventory_file,user_id): 
    with open(inventory_file.name,'wb+') as destination:
        for chunk in inventory_file.chunks():
            destination.write(chunk)
    reader = csv.reader(open(inventory_file.name,'rb'))

open 获取您要打开的文件的名称,因此您应该使用inventory_filename 字段中提供的名称。

来自UploadedFile documentation

上传的文件名

The name of the uploaded file (e.g. my_file.txt).

【讨论】:

  • 以及如何将该文件写入不同的目录而不是项目目录
  • 写入不同的文件夹with open(/path/to/inventory_file.name,'wb+') as destination.
猜你喜欢
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 2018-05-14
  • 1970-01-01
  • 2018-07-24
相关资源
最近更新 更多