source: vlo/branches/vlo-3.0/vlo-solr/src/main/webapp/js/lib/jquery.ajaxfileupload.js @ 4734

Last change on this file since 4734 was 4734, checked in by teckart@informatik.uni-leipzig.de, 10 years ago

Added files for Solr admin interface (directories: css, img, js, tpl + admin.html), updated web.xml

File size: 6.9 KB
Line 
1/*
2* Copyright (c) 2011 Jordan Feldstein
3
4Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
6The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
8THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9 */
10
11// Original code from: https://github.com/jfeldstein/jQuery.AjaxFileUpload.js https://github.com/jfeldstein/jQuery.AjaxFileUpload.js/commit/9dd56b4161cbed138287d3ae29a476bb59eb5fc4
12// All modifications are BSD licensed
13// GSI: Modifications made to support immediate upload
14/*
15 //
16 //  - Ajaxifies an individual <input type="file">
17 //  - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
18 //  - Allows for extra parameters to be included with the file
19 //  - onStart callback can cancel the upload by returning false
20 */
21
22
23(function ($) {
24  $.fn.ajaxfileupload = function (options) {
25    var settings = {
26      params: {},
27      action: '',
28      onStart: function () {
29        console.log('starting upload');
30        console.log(this);
31      },
32      onComplete: function (response) {
33        console.log('got response: ');
34        console.log(response);
35        console.log(this);
36      },
37      onCancel: function () {
38        console.log('cancelling: ');
39        console.log(this);
40      },
41      validate_extensions: true,
42      valid_extensions: ['gif', 'png', 'jpg', 'jpeg'],
43      submit_button: null,
44      upload_now: false
45    };
46
47    var uploading_file = false;
48
49    if (options) {
50      $.extend(settings, options);
51    }
52
53
54    // 'this' is a jQuery collection of one or more (hopefully)
55    //  file elements, but doesn't check for this yet
56    return this.each(function () {
57      var $element = $(this);
58      /*
59       // Internal handler that tries to parse the response
60       //  and clean up after ourselves.
61       */
62      var handleResponse = function (loadedFrame, element) {
63        var response, responseStr = loadedFrame.contentWindow.document.body.innerHTML;
64        try {
65          //response = $.parseJSON($.trim(responseStr));
66          response = JSON.parse(responseStr);
67        } catch (e) {
68          response = responseStr;
69        }
70
71        // Tear-down the wrapper form
72        element.siblings().remove();
73        element.unwrap();
74
75        uploading_file = false;
76
77        // Pass back to the user
78        settings.onComplete.apply(element, [response, settings.params]);
79      };
80      /*
81       // Wraps element in a <form> tag, and inserts hidden inputs for each
82       //  key:value pair in settings.params so they can be sent along with
83       //  the upload. Then, creates an iframe that the whole thing is
84       //  uploaded through.
85       */
86      var wrapElement = function (element) {
87        // Create an iframe to submit through, using a semi-unique ID
88        var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
89        $('body').after('<iframe width="0" height="0" style="display:none;" name="' + frame_id + '" id="' + frame_id + '"/>');
90        $('#' + frame_id).load(function () {
91          handleResponse(this, element);
92        });
93        console.log("settings.action: " + settings.action);
94        // Wrap it in a form
95        element.wrap(function () {
96          return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="' + frame_id + '" />'
97        })
98          // Insert <input type='hidden'>'s for each param
99            .before(function () {
100              var key, html = '';
101              for (key in settings.params) {
102                var paramVal = settings.params[key];
103                if (typeof paramVal === 'function') {
104                  paramVal = paramVal();
105                }
106                html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
107              }
108              return html;
109            });
110      }
111
112      var upload_file = function () {
113        if ($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
114
115        // make sure extension is valid
116        var ext = $element.val().split('.').pop().toLowerCase();
117        if (true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1) {
118          // Pass back to the user
119          settings.onComplete.apply($element, [
120            {status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'},
121            settings.params
122          ]);
123        } else {
124          uploading_file = true;
125
126          // Creates the form, extra inputs and iframe used to
127          //  submit / upload the file
128          wrapElement($element);
129
130          // Call user-supplied (or default) onStart(), setting
131          //  it's this context to the file DOM element
132          var ret = settings.onStart.apply($element, [settings.params]);
133
134          // let onStart have the option to cancel the upload
135          if (ret !== false) {
136            $element.parent('form').submit(function (e) {
137              e.stopPropagation();
138            }).submit();
139          }
140        }
141      };
142      if (settings.upload_now) {
143        if (!uploading_file) {
144          console.log("uploading now");
145          upload_file();
146        }
147      }
148      // Skip elements that are already setup. May replace this
149      //  with uninit() later, to allow updating that settings
150      if ($element.data('ajaxUploader-setup') === true) return;
151
152      $element.change(function () {
153        // since a new image was selected, reset the marker
154        uploading_file = false;
155
156        // only update the file from here if we haven't assigned a submit button
157        if (settings.submit_button == null) {
158          console.log("uploading");
159          upload_file();
160        }
161      });
162
163      if (settings.submit_button == null) {
164        // do nothing
165      } else {
166        settings.submit_button.click(function () {
167          console.log("uploading: " + uploading_file);
168          // only attempt to upload file if we're not uploading
169          if (!uploading_file) {
170            upload_file();
171          }
172        });
173      }
174
175
176      // Mark this element as setup
177      $element.data('ajaxUploader-setup', true);
178
179
180    });
181  }
182})(jQuery)
Note: See TracBrowser for help on using the repository browser.