环境
Django==3.24
DRF==3.11
boto3==1.16
django存储==1.10
我想在上传到s3之前更改文件名,而不保存在DB(模型)中。
我试过了。
# in Post request
files = request.FILES.getlist('files')
res = []
for file in files:
random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
ext = file.name.split('.')[-1]
file_name = f'{random_car}.{ext}'
# -------- try start ---------
# I want to change file name to file_name
# This code throws an error.
# FileNotFoundError: [Errno 2] No such file or directory: '8.jpeg' -> 'kVuepnuR.jpeg'
os.rename(file.name, file_name)
# -------- try end ---------
file_path_within_bucket = os.path.join(
file_directory_within_bucket,
file.name
)
default_storage.save(file_path_within_bucket, file)
file_url = default_storage.url(file_path_within_bucket)
res.append(file_url)
如果InMemoryUploadedFile,我如何更改名称?
我找到了一种方法来解决它并分享它。
random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
ext = file.name.split('.')[-1]
file_name = f'{random_car}.{ext}'
file_path_within_bucket = os.path.join(
file_directory_within_bucket,
f"{file_name}"
)
的istead
random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
ext = file.name.split('.')[-1]
file_name = f'{random_car}.{ext}'
file_path_within_bucket = os.path.join(
file_directory_within_bucket,
file.name
)