Skip to main content
 首页 » 编程设计

python之在 python django 中使用名称上传的文件

2025年05月04日41del

我正在使用这段代码:

  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')) 

但它给出了以下错误:

Exception Type: IOError

Exception Value: [Errno 36] File name too long: 'Se .. .. . .

请您参考如下方法:

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

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_file 的 name 字段中提供的名称.

来自 UploadedFile documentation :

UploadedFile.name

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