[英]django save image in zip
Client upload zip.客户端上传 zip。
Picture after decompression.解压后的图片。
I want to save the picture to the specified location.我想把图片保存到指定位置。
But my code cannot be saved to the specified location但我的代码无法保存到指定位置
How to do?怎么做?
models.py模型.py
def get_upload_path(instance, filename):
return f'register/{instance.owner.job_number}/{filename}'
class UserRegister(models.Model):
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
image = models.ImageField(upload_to=get_upload_path)
class Meta:
db_table = 'UserRegister'
views意见
class AddsUser(View):
def get(self, request):
data = {
'title': 'AddsUser'
}
return render(request, './User/adds_user.html', data)
def post(self, request):
job_number = request.POST.get('job_number')
zip_file = request.FILES.get('zip')
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dir_name = uuid.uuid4().hex
zip_dir_path = f'./temp_zip/{dir_name}'
# Save zip.
with open(f'{zip_dir_path}.zip', 'wb') as files:
for i in zip_file.chunks():
files.write(i)
files.flush()
os.mkdir(zip_dir_path) # Create folder.
os.system(f'unzip {zip_dir_path}.zip -d {zip_dir_path}') # unzip
# Read all pictures in the folder.
for image_name in os.listdir(zip_dir_path):
image_path = f"{zip_dir_path}/{image_name}"
user_profile = UserProfile.objects.create(job_number=job_number, date=date)
user_register = UserRegister.objects.create(owner_id=user_profile.id,
image=image_path)
return redirect(reverse('admin:adds_user'))
This method will not store the picture in the location I specified.此方法不会将图片存储在我指定的位置。
Now database:现在数据库:
./temp_zip/4b9811b0a3c5429cb320cec1357c1099/247688.jpg
I hope the result is:我希望结果是:
f'register/{instance.owner.job_number}/{filename}'
register/123/247688.jpg'
user_register = UserRegister.objects.create(owner_id=user_profile.id,
image=image_path)
change to改成
with open(image_path, 'rb') as image_file:
user_register = UserRegister()
user_register.owner_id = user_profile.id
user_register.image.save(image_name, ContentFile(image_file.read()))
This will save the image specification to get_upload_path
.这会将图像规范保存到get_upload_path
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.