Merge pull request #1426 from anandpdoshi/fix/validate-upload-size-in-js

[fix] Validate max file size before upload
This commit is contained in:
Anand Doshi 2015-11-25 11:46:35 +05:30
commit cf05af9444
2 changed files with 29 additions and 3 deletions

View file

@ -9,7 +9,7 @@ naming for same name files: file.gif, file-1.gif, file-2.gif etc
"""
import frappe, frappe.utils
from frappe.utils.file_manager import delete_file_data_content, get_content_hash
from frappe.utils.file_manager import delete_file_data_content, get_content_hash, get_random_filename
from frappe import _
from frappe.utils.nestedset import NestedSet
@ -172,9 +172,19 @@ class File(NestedSet):
raise
image = Image.open(StringIO.StringIO(r.content))
filename, extn = self.file_url.rsplit("/", 1)[1].rsplit(".", 1)
mimetype = mimetypes.guess_type(filename + "." + extn)[0]
try:
filename, extn = self.file_url.rsplit("/", 1)[1].rsplit(".", 1)
except ValueError:
# the case when the file url doesn't have filename or extension
# but is fetched due to a query string. example: https://encrypted-tbn3.gstatic.com/images?q=something
filename = get_random_filename()
extn = ""
mimetype = None
if extn:
mimetype = mimetypes.guess_type(filename + "." + extn)[0]
if mimetype is None or not mimetype.startswith("image/"):
# detect file extension by reading image header properties
extn = imghdr.what(filename + "." + extn, h=r.content)

View file

@ -78,6 +78,10 @@ frappe.upload = {
var dataurl = null;
var _upload_file = function() {
if (args.file_size) {
frappe.upload.validate_max_file_size(args.file_size);
}
if(opts.on_attach) {
opts.on_attach(args, dataurl)
} else {
@ -133,12 +137,14 @@ frappe.upload = {
frappe.utils.resize_image(freader, function(_dataurl) {
dataurl = _dataurl;
args.filedata = _dataurl.split(",")[1];
args.file_size = Math.round(args.filedata.length * 3 / 4);
console.log("resized!")
_upload_file();
})
} else {
dataurl = freader.result;
args.filedata = freader.result.split(",")[1];
args.file_size = fileobj.size;
_upload_file();
}
};
@ -157,5 +163,15 @@ frappe.upload = {
return decodeURIComponent(escape(atob(a)));
},
validate_max_file_size: function(file_size) {
var max_file_size = frappe.boot.max_file_size || 5242880;
if (file_size > max_file_size) {
// validate max file size
frappe.throw(__("File size exceeded the maximum allowed size of {0} MB", [max_file_size / 1048576]));
}
}
}