更改上传文件django的文件名

时间:2016-08-04 03:36:40

标签: python 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 个答案:

答案 0 :(得分: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)