2016-08-04 110 views
0

這就是我想要做的。我創建了一個上傳文件的方法,但是我想更改文件名。我能夠改變文件名,但我也失去了擴展名。更改上傳文件的文件名django

這是我的代碼怎麼看:

def upload_delivery_to_media(self,deliveryId, deliveryFile): 

    with open('/app/media/TaskDelivery/'+str(delivery), 'wb+') as destination: 
     for chunk in deliveryFile.chunks(): 
      destination.write(chunk) 

    return "Done uploading" 

但文件看起來像324329432840932只有我期待像324329432840932.jpg

+1

'str(delivery)'應該是'str(deliveryId)',對不對?你可以附加一個'.jpg'到文件名。 –

+0

以及我也做了它,但不是所有的文件只有.jpg。其中一些是.gif,.pdf等 –

+1

您可以將原始文件名分割爲'.'和存儲擴展名。然後將其附加到您的新文件名。 –

回答

0

這是更好地使用splitext代替方法split()

import os 
from django.conf import settings 

def upload_delivery_to_media(self, delivery_id, delivery_file): 
    _, ext = os.path.splitext(delivery_file.name) 
    with open(os.path.join(settings.MEDIA_ROOT, 'TaskDelivery', '{}{}'.format(delivery_id, ext)), 'wb') as destination: 
     for chunk in delivery_file.chunks(): 
      destination.write(chunk)