How to validate a file in a javascript
Hello!
I am trying to show the errors that can occur by uploading a file (file extension, size).
I am using an adapted version of Jquery Fiel Upload for Ruby on Rails
I need to validate a file (ending of a file, size of the file) before uploading and as nobody has an idea how to do it with JSON I want to ask if somebody knows how to do it in a following javascript:
- <script type="text/javascript" charset="utf-8">
- $(function () {
- // Initialize the jQuery File Upload widget:
- $('#fileupload').fileupload();
- //
- // Load existing files:
- $.getJSON($('#fileupload').prop('action'), function (files) {
- var fu = $('#fileupload').data('fileupload'),
- template;
- fu._adjustMaxNumberOfFiles(-files.length);
- console.log(files);
- template = fu._renderDownload(files)
- .appendTo($('#fileupload .files'));
- // Force reflow:
- fu._reflow = fu._transition && template.length &&
- template[0].offsetWidth;
- template.addClass('in');
- $('#loading').remove();
- });
-
- });
- </script>
I am thinking of something like this (the code downstairs) but I need to rewrite the above code to present validation line `
- types = /(\.|\/)(gif|jpe?g|png)$/i`
and to have a error-message
- `alert("#{file.name} is not a gif, jpeg, or png image file")`
. As I am not god at writing javascripts I am asking for help.
- jQuery ->
- $('#new_painting').fileupload
- dataType: "script"
- add: (e, data) ->
- types = /(\.|\/)(gif|jpe?g|png)$/i
- file = data.files[0]
- if types.test(file.type) || types.test(file.name)
- data.context = $(tmpl("template-upload", file))
- $('#new_painting').append(data.context)
- data.submit()
- else
- alert("#{file.name} is not a gif, jpeg, or png image file")
- progress: (e, data) ->
- if data.context
- progress = parseInt(data.loaded / data.total * 100, 10)
- data.context.find('.bar').css('width', progress + '%')
I know that it is a very bad validation to check the extension but I still need it.
Many thanks in advanced.