Commit 023f0ca3 authored by Jerome Mariette's avatar Jerome Mariette
Browse files

first version of upload (buggy)

parent 31328b93
......@@ -41,7 +41,7 @@ from workflows.types import *
import jflow.utils as utils
from cctools.util import time_format
# function in charge to upload large files
class myFieldStorage(cgi.FieldStorage):
"""Our version uses a named temporary file instead of the default
non-named file; keeping it visibile (named), allows us to create a
......@@ -50,15 +50,20 @@ class myFieldStorage(cgi.FieldStorage):
def make_file(self, binary=None):
return tempfile.NamedTemporaryFile()
def noBodyProcess():
"""Sets cherrypy.request.process_request_body = False, giving
us direct control of the file upload destination. By default
cherrypy loads it to memory, we are directing it to disk."""
cherrypy.request.process_request_body = False
cherrypy.tools.noBodyProcess = cherrypy.Tool('before_finalize', noBodyProcess)
# define functions in charge to handle cross domain calls
def CORS():
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'OPTIONS, GET, POST'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Content-Range, Content-Disposition'
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.tools.noBodyProcess = cherrypy.Tool('before_request_body', noBodyProcess)
class JFlowServer (object):
......@@ -129,64 +134,7 @@ class JFlowServer (object):
"components": components}
return status
@cherrypy.expose
@jsonify
def index(self):
"""Simplest possible HTML file upload form. Note that the encoding
type must be multipart/form-data."""
return """
<html>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
File: <input type="file" name="theFile"/> <br/>
<input type="submit"/>
</form>
</body>
</html>
"""
@cherrypy.expose
@cherrypy.tools.noBodyProcess()
@jsonify
def upload(self, theFile):
"""upload action
We use our variation of cgi.FieldStorage to parse the MIME
encoded HTML form data containing the file."""
print theFile
# # the file transfer can take a long time; by default cherrypy
# # limits responses to 300s; we increase it to 1h
# cherrypy.response.timeout = 3600
#
# # convert the header keys to lower case
# lcHDRS = {}
# for key, val in cherrypy.request.headers.iteritems():
# lcHDRS[key.lower()] = val
#
# print lcHDRS
#
# # at this point we could limit the upload on content-length...
# # incomingBytes = int(lcHDRS['content-length'])
#
# # create our version of cgi.FieldStorage to parse the MIME encoded
# # form data where the file is contained
# formFields = myFieldStorage(fp=cherrypy.request.rfile,
# headers=lcHDRS,
# environ={'REQUEST_METHOD':'POST'},
# keep_blank_values=True)
# #print formFields
# # we now create a 2nd link to the file, using the submitted
# # filename; if we renamed, there would be a failure because
# # the NamedTemporaryFile, used by our version of cgi.FieldStorage,
# # explicitly deletes the original filename
# theFile = formFields['theFile']
# print theFile
# os.link(theFile.file.name, '/tmp/'+theFile.filename)
#
# return "ok, got it filename='%s'" % theFile.filename
@cherrypy.expose
@jsonify
def get_available_workflows(self, **kwargs):
......@@ -259,7 +207,50 @@ class JFlowServer (object):
self.wfmanager.rerun_workflow(kwargs["workflow_id"])
workflow = self.wfmanager.get_workflow(kwargs["workflow_id"])
return self.jsonify_workflow_status(workflow)
@cherrypy.expose
@cherrypy.tools.noBodyProcess()
@cherrypy.tools.CORS()
def upload(self, **kwargs):
file = kwargs.keys()[0]
# the file transfer can take a long time; by default cherrypy
# limits responses to 300s; we increase it to 1h
cherrypy.response.timeout = 3600
# convert the header keys to lower case
lcHDRS = {}
for key, val in cherrypy.request.headers.iteritems():
lcHDRS[key.lower()] = val
# at this point we could limit the upload on content-length...
# incomingBytes = int(lcHDRS['content-length'])
# create our version of cgi.FieldStorage to parse the MIME encoded
# form data where the file is contained
print "**********************************************************"
print cherrypy.request.rfile
print "**********************************************************"
formFields = myFieldStorage(fp=cherrypy.request.rfile,
headers=lcHDRS,
environ={'REQUEST_METHOD':'POST'},
keep_blank_values=True)
# we now create a 2nd link to the file, using the submitted
# filename; if we renamed, there would be a failure because
# the NamedTemporaryFile, used by our version of cgi.FieldStorage,
# explicitly deletes the original filename
print "..............................................................."
print formFields
print "..............................................................."
theFile = formFields[file]
print theFile
os.link(theFile.file.name, '/tmp/'+theFile.filename)
return "ok, got it filename='%s'" % theFile.filename
@cherrypy.expose
@jsonify
def get_workflows_status(self, **kwargs):
......@@ -297,6 +288,7 @@ class JFlowServer (object):
except Exception, e:
return str(e)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
......@@ -318,9 +310,8 @@ if __name__ == '__main__':
# increase server socket timeout to 60s; we are more tolerant of bad
# quality client-server connections (cherrypy's defult is 10s)
cherrypy.server.socket_timeout = 60
cherrypy.config.update({'server.socket_host': socket_opts[0],
'server.socket_port': socket_opts[1]})
# start the server
cherrypy.quickstart(JFlowServer())
\ No newline at end of file
......@@ -175,13 +175,16 @@ jQuery.validator.addMethod("exclude_required", function(value, element, options)
$("#workflow_form :checkbox").each(function(){
if (!$(this).prop('checked')) { params += $(this).attr("name") + "=false&"; }
});
$.ajax({
$this.$element.trigger('upload.files');
/*$.ajax({
url: this.options.serverURL + '/run_workflow?' + params + 'callback=?',
dataType: "json",
success: function(running_wf) {
$this.$element.trigger('run', running_wf);
}
});
});*/
}
}
......@@ -252,65 +255,15 @@ jQuery.validator.addMethod("exclude_required", function(value, element, options)
});
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'http://localhost/upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'localhost') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
$(".fileupload").fileupload({
url: $this.options.serverURL + "/upload",
forceIframeTransport: true,
add: function (e, data) {
$this.$element.on("upload.files", function() {
data.submit();
});
}
});
$('.date').datepicker().on('changeDate', function(ev){ $('.date').datepicker('hide');} );
......@@ -448,9 +401,8 @@ jQuery.validator.addMethod("exclude_required", function(value, element, options)
' </ul>',
' </div>',
' <div class="input-append">',
' <input id="${param.name}" name="${param.name}" class="${param.group} ${input_size} span2 upload" type="text" value="${param.default}">',
' <input id="${param.name}" name="${param.name}" class="${param.group} ${input_size} span2" type="text" value="${param.default}">',
' <button id="urlfile_btn_${param.name}" style="display: none;" class="btn" type="button"><i class="icon-search"></i></button>',
' <input name="browse_${param.name}" id="browse_${param.name}" style="display: none;" type="file">',
' </div>',
' </div>',
// if param is a boolean
......@@ -523,8 +475,15 @@ jQuery.validator.addMethod("exclude_required", function(value, element, options)
'{{/if}}',
'</fieldset>',
'</form>',
'<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">',
'File: <input id="fileupload" type="file" name="theFile"/> <br/>',
'<form method="post" enctype="multipart/form-data" style="display:none;">',
' {{each(gindex, group) workflow.groups}}',
' {{each(index, param) workflow.parameters_per_groups[group]}}',
// if param is an inputfile
' {{if param.type == "inputfile"}}',
' <input name="browse_${param.name}" id="browse_${param.name}" class="fileupload" type="file">',
' {{/if}}',
' {{/each}}',
' {{/each}}',
'</form>'].join('\n'),
workflowClass: null,
displayRunButton: true,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment