-->

File upload functionality in google closure?

2019-06-01 19:44发布

问题:

I am creating a project on google app engine. Here I am trying to upload a file to blobstore. I have an html file with multiple forms, where each form has a file upload button

<input type="file">

Now as soon as user selects a file using this button the file must start uploading to GAE blobstore.
I have the python code which can do this uploading stuff but I am not able to link my backend (python) code to the file I've browsed. Also, as there are multiple forms the page must not get refreshed.

I have found a solution to page refresh in google closure(using a pop up), but it is not desire in my project. I believe there is no other way in closure library.

I am trying to do it using ajax call but my very limited knowledge of ajax is preventing me to get the dsired results.

Using JQUERY is not an option.

I hope my question is clear, please revert back if not.

Any help is much appreciated.

Thanks

回答1:

Google Closure provides an IframeIo class that can post your file (without refreshing the page), documentation available here, http://closure-library.googlecode.com/svn/docs/class_goog_net_IframeIo.html

We implemented a wrapper on IframeIo (available under the BSD license) to present the user with a file upload input and the post to a URL when they select a file. Source available at, https://code.google.com/p/prestans/source/browse/trunk/client/closure/ui/IframeFileUpload.js

Handling success / failure codes are little tricky, depending on what you return from your Blobstore file upload handler.



回答2:

What i used is to use the onchange of the input/file-control. The onChange returns the control and the mime-type. From within the onchange you can access the filelist array of the control to obtain the filename. Using the filename you can use the FileReader to load the actual data. This data can be uploaded using a xhr post (and converting it to base64) to the server. Something like:

function onChange(control, mimetype) {
var f = control.files;
if (f.length) {
  var reader = new FileReader;
  reader.onload = function() {
    // Post using xhr
  }
  reader.readAsBinaryString(f)
}

Please not the FileReader object is not present on all browsers... (Chrome does support it!)