我有一个django项目,要求用户在文章中使用多个图像。我正在使用Django并使用Zappa部署它。我知道在Zappa中,页面加载中的最大尺寸为10MB。我有1个帖子图像和7个准备图像。当用户添加7个大文件然后命中时提交时,我会在下面获得错误
http413:有效载荷太大 - 服务器拒绝处理一个 请求是因为请求实体大于服务器 愿意或能够处理。
是否有一种方法可以一次添加图像,而不是一次添加所有图像,以免曲线打破,我不会收到上述错误
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
title = models.CharField(max_length=250, unique=True)
message = models.TextField()
post_image = models.ImageField(upload_to='post_images/')
def save(self, *args, **kwargs):
im = Image.open(self.post_image)
super(Post, self).save()
output = BytesIO()
basewidth = 700
wpercent = (basewidth / float(im.size[0]))
hsize = int((float(im.size[1]) * float(wpercent)))
im = im.resize((basewidth, hsize))
# after modifications, save it to the output
im.save(output, format='JPEG', quality=40)
output.seek(0)
self.post_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.post_image.name.split('.')[0], 'image/jpeg',
sys.getsizeof(output), None)
super().save(*args, **kwargs)
然后,我有一个模型,将多个图像添加到帖子
class Prep (models.Model): #(Images)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep')
image = models.ImageField(upload_to='post_prep_images/', blank=True, null=True)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
im = Image.open(self.image)
output = BytesIO()
basewidth = 700
wpercent = (basewidth / float(im.size[0]))
hsize = int((float(im.size[1]) * float(wpercent)))
super(Prep, self).save()
im = im.resize((basewidth, hsize))
# after modifications, save it to the output
im.save(output, format='JPEG', quality=300)
output.seek(0)
# change the imagefield value to be the newley modifed image value
self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg',
sys.getsizeof(output), None)
super(Prep, self).save()
在我的视图中。
@login_required
def post_create(request):
ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7, max_num=7,
min_num=2)
if request.method == "POST":
form = PostForm(request.POST or None, request.FILES or None)
formset = ImageFormSet(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
post_user = request.user
for f in formset.cleaned_data:
try:
photo = Prep(post=instance, image=f['image']
photo.save()
except Exception as e:
break
return redirect('posts:single', username=instance.user.username, slug=instance.slug)
else:
form = PostForm()
formset = ImageFormSet(queryset=Prep.objects.none())
context = {
'form': form,
'formset': formset,
}
return render(request, 'posts/post_form.html', context)
10 mb限制不是Zappa限制,而是API网关限制。它是AWS设定的极限,无法增加它。
您可以沿着通过API网关到达S3上传大量有效载荷的相当复杂的途径。在本文中详细解释:https://sookocheff.com/post/api/uploading-large-payloads-though-api-gateway/
,或者您可以执行一些前端魔术并提出几个较小的请求,其中一个是您上传的每张照片。