Prevent uploading too large image file (#416)

This commit is contained in:
TAKAHASHI Shuuji 2023-01-16 02:29:18 +09:00 committed by GitHub
parent 94fe247b17
commit 5e65d569bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 3 deletions

View File

@ -204,7 +204,30 @@ class ImageUpload(FormView):
template_name = "activities/_image_upload.html"
class form_class(forms.Form):
image = forms.ImageField()
image = forms.ImageField(
widget=forms.FileInput(
attrs={
"_": f"""
on change
if me.files[0].size > {settings.SETUP.MEDIA_MAX_IMAGE_FILESIZE_MB * 1024 ** 2}
add [@disabled=] to #upload
remove <ul.errorlist/>
make <ul.errorlist/> called errorlist
make <li/> called error
set size_in_mb to (me.files[0].size / 1024 / 1024).toFixed(2)
put 'File must be 10MB or less (actual: ' + size_in_mb + 'MB)' into error
put error into errorlist
put errorlist before me
else
remove @disabled from #upload
remove <ul.errorlist/>
end
end
"""
}
)
)
description = forms.CharField(required=False)
def clean_image(self):
@ -214,7 +237,9 @@ class ImageUpload(FormView):
if value.size > max_bytes:
# Erase the file from our data to stop trying to show it again
self.files = {}
raise forms.ValidationError(f"File must be {max_mb}MB or less")
raise forms.ValidationError(
f"File must be {max_mb}MB or less (actual: {value.size / 1024 ** 2:.2f})"
)
return value
def form_invalid(self, form):

View File

@ -1034,6 +1034,7 @@ button.toggle,
button[disabled],
.button[disabled] {
background: var(--color-button-disabled);
cursor: not-allowed;
}
button.left,

View File

@ -9,7 +9,7 @@
{% include "forms/_field.html" with field=form.image %}
{% include "forms/_field.html" with field=form.description %}
<div class="buttons">
<button _="on click show #attachmentProgress with display:block then hide me">Upload</button>
<button id="upload" _="on click show #attachmentProgress with display:block then hide me">Upload</button>
<progress id="attachmentProgress" value="0" max="100"></progress>
</div>
</form>