Skip to content

Instantly share code, notes, and snippets.

@hzx
Created February 14, 2012 22:36
Show Gist options
  • Select an option

  • Save hzx/1831144 to your computer and use it in GitHub Desktop.

Select an option

Save hzx/1831144 to your computer and use it in GitHub Desktop.
iframe uploading file
class UploadFile {
ObservableValue<Object> observableResponse;
ObservableEvent observableError;
UploadFile(this.url, [bool multiple=false])
: _onInputFileChangeWrap = _onInputFileChange
, _onFrameLoadWrap = _onFrameLoad {
String multipleAttr = multiple ? 'multiple' : '';
_node = _render(url, multipleAttr);
document.body.nodes.add(_node);
_enter();
}
Element _node;
Function _onInputFileChangeWrap;
Function _onFrameLoadWrap;
String url;
List<Map> _attrs;
static int id = 1;
Element _render(String url, String multipleAttr) {
String targetName = 'uploadfile-target-${UploadFile.id++}';
String xsrf = CookieUtil.getValue('_xsrf');
Element element = new Element.html('''
<div class="uploadfile">
<iframe name="$targetName"></iframe>
<form method="POST" action="$url" enctype="multipart/form-data" target="$targetName">
<input type="hidden" name="_xsrf" value="$xsrf"/>
<input type="file" name="new-file" class="new-file" $multipleAttr/>
<div class="attrs"></div>
</form>
</div>
''');
return element;
}
void _enter() {
// listen input change event
_node.query('.new-file').on.change.add(_onInputFileChangeWrap);
// listen frame load event
_node.query('iframe').on.load.add(_onFrameLoadWrap);
}
void exit() {
_node.query('.new-file').on.change.remove(_onInputFileChangeWrap);
_node.query('iframe').on.load.remove(_onFrameLoadWrap);
}
void showDialog(List<Map> attrs) {
_attrs = attrs;
InputElement input = _node.query('.new-file');
input.click();
}
void _onInputFileChange(e) {
// add additional attributes
Element element = _node.query('.attrs');
element.nodes.clear();
for (Map attr in _attrs) {
element.nodes.add(new Element.html('<input type="hidden" name="${attr["name"]}" value="${attr["value"]}"/>'));
}
// submit form
FormElement form = _node.query('form');
form.submit();
}
void _onFrameLoad(e) {
IFrameElement iframe = _node.query('iframe');
var response = iframe.contentDocument.body.text;
// parse json and process exception
try {
observableResponse.value = JSON.parse(response);
} catch (ex) {
// if error then response first 3 symbols is error status
int status = Math.parseInt(response.substring(0, 3));
observableError.notify({'status':status, 'statusText':response});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment