Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

VUpload.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright 2000-2013 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import com.google.gwt.core.client.GWT;
  18. import com.google.gwt.core.client.Scheduler;
  19. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  20. import com.google.gwt.dom.client.DivElement;
  21. import com.google.gwt.dom.client.Document;
  22. import com.google.gwt.dom.client.FormElement;
  23. import com.google.gwt.event.dom.client.ClickEvent;
  24. import com.google.gwt.event.dom.client.ClickHandler;
  25. import com.google.gwt.user.client.Command;
  26. import com.google.gwt.user.client.Event;
  27. import com.google.gwt.user.client.Timer;
  28. import com.google.gwt.user.client.ui.FileUpload;
  29. import com.google.gwt.user.client.ui.FlowPanel;
  30. import com.google.gwt.user.client.ui.FormPanel;
  31. import com.google.gwt.user.client.ui.Hidden;
  32. import com.google.gwt.user.client.ui.Panel;
  33. import com.google.gwt.user.client.ui.SimplePanel;
  34. import com.vaadin.client.ApplicationConnection;
  35. import com.vaadin.client.BrowserInfo;
  36. import com.vaadin.client.VConsole;
  37. import com.vaadin.client.ui.upload.UploadIFrameOnloadStrategy;
  38. /**
  39. *
  40. * Note, we are not using GWT FormPanel as we want to listen submitcomplete
  41. * events even though the upload component is already detached.
  42. *
  43. */
  44. public class VUpload extends SimplePanel {
  45. private final class MyFileUpload extends FileUpload {
  46. @Override
  47. public void onBrowserEvent(Event event) {
  48. super.onBrowserEvent(event);
  49. if (event.getTypeInt() == Event.ONCHANGE) {
  50. if (immediate && fu.getFilename() != null
  51. && !"".equals(fu.getFilename())) {
  52. submit();
  53. }
  54. } else if (BrowserInfo.get().isIE()
  55. && event.getTypeInt() == Event.ONFOCUS) {
  56. // IE and user has clicked on hidden textarea part of upload
  57. // field. Manually open file selector, other browsers do it by
  58. // default.
  59. fireNativeClick(fu.getElement());
  60. // also remove focus to enable hack if user presses cancel
  61. // button
  62. fireNativeBlur(fu.getElement());
  63. }
  64. }
  65. }
  66. public static final String CLASSNAME = "v-upload";
  67. /**
  68. * FileUpload component that opens native OS dialog to select file.
  69. * <p>
  70. * For internal use only. May be removed or replaced in the future.
  71. */
  72. public FileUpload fu = new MyFileUpload();
  73. Panel panel = new FlowPanel();
  74. UploadIFrameOnloadStrategy onloadstrategy = GWT
  75. .create(UploadIFrameOnloadStrategy.class);
  76. /** For internal use only. May be removed or replaced in the future. */
  77. public ApplicationConnection client;
  78. /** For internal use only. May be removed or replaced in the future. */
  79. public String paintableId;
  80. /**
  81. * Button that initiates uploading.
  82. * <p>
  83. * For internal use only. May be removed or replaced in the future.
  84. */
  85. public final VButton submitButton;
  86. /**
  87. * When expecting big files, programmer may initiate some UI changes when
  88. * uploading the file starts. Bit after submitting file we'll visit the
  89. * server to check possible changes.
  90. * <p>
  91. * For internal use only. May be removed or replaced in the future.
  92. */
  93. public Timer t;
  94. /**
  95. * some browsers tries to send form twice if submit is called in button
  96. * click handler, some don't submit at all without it, so we need to track
  97. * if form is already being submitted
  98. */
  99. private boolean submitted = false;
  100. private boolean enabled = true;
  101. private boolean immediate;
  102. private Hidden maxfilesize = new Hidden();
  103. /** For internal use only. May be removed or replaced in the future. */
  104. public FormElement element;
  105. private com.google.gwt.dom.client.Element synthesizedFrame;
  106. /** For internal use only. May be removed or replaced in the future. */
  107. public int nextUploadId;
  108. public VUpload() {
  109. super(com.google.gwt.dom.client.Document.get().createFormElement());
  110. element = getElement().cast();
  111. setEncoding(getElement(), FormPanel.ENCODING_MULTIPART);
  112. element.setMethod(FormPanel.METHOD_POST);
  113. setWidget(panel);
  114. panel.add(maxfilesize);
  115. panel.add(fu);
  116. submitButton = new VButton();
  117. submitButton.addClickHandler(new ClickHandler() {
  118. @Override
  119. public void onClick(ClickEvent event) {
  120. if (immediate) {
  121. // fire click on upload (eg. focused button and hit space)
  122. fireNativeClick(fu.getElement());
  123. } else {
  124. submit();
  125. }
  126. }
  127. });
  128. panel.add(submitButton);
  129. setStyleName(CLASSNAME);
  130. }
  131. private static native void setEncoding(
  132. com.google.gwt.user.client.Element form, String encoding)
  133. /*-{
  134. form.enctype = encoding;
  135. // For IE8
  136. form.encoding = encoding;
  137. }-*/;
  138. /** For internal use only. May be removed or replaced in the future. */
  139. public void setImmediate(boolean booleanAttribute) {
  140. if (immediate != booleanAttribute) {
  141. immediate = booleanAttribute;
  142. if (immediate) {
  143. fu.sinkEvents(Event.ONCHANGE);
  144. fu.sinkEvents(Event.ONFOCUS);
  145. }
  146. }
  147. setStyleName(getElement(), CLASSNAME + "-immediate", immediate);
  148. }
  149. private static native void fireNativeClick(
  150. com.google.gwt.user.client.Element element)
  151. /*-{
  152. element.click();
  153. }-*/;
  154. private static native void fireNativeBlur(
  155. com.google.gwt.user.client.Element element)
  156. /*-{
  157. element.blur();
  158. }-*/;
  159. /** For internal use only. May be removed or replaced in the future. */
  160. public void disableUpload() {
  161. submitButton.setEnabled(false);
  162. if (!submitted) {
  163. // Cannot disable the fileupload while submitting or the file won't
  164. // be submitted at all
  165. fu.getElement().setPropertyBoolean("disabled", true);
  166. }
  167. enabled = false;
  168. }
  169. /** For internal use only. May be removed or replaced in the future. */
  170. public void enableUpload() {
  171. submitButton.setEnabled(true);
  172. fu.getElement().setPropertyBoolean("disabled", false);
  173. enabled = true;
  174. if (submitted) {
  175. /*
  176. * An old request is still in progress (most likely cancelled),
  177. * ditching that target frame to make it possible to send a new
  178. * file. A new target frame is created later."
  179. */
  180. cleanTargetFrame();
  181. submitted = false;
  182. }
  183. }
  184. /**
  185. * Re-creates file input field and populates panel. This is needed as we
  186. * want to clear existing values from our current file input field.
  187. */
  188. private void rebuildPanel() {
  189. panel.remove(submitButton);
  190. panel.remove(fu);
  191. fu = new MyFileUpload();
  192. fu.setName(paintableId + "_file");
  193. fu.getElement().setPropertyBoolean("disabled", !enabled);
  194. panel.add(fu);
  195. panel.add(submitButton);
  196. if (immediate) {
  197. fu.sinkEvents(Event.ONCHANGE);
  198. }
  199. }
  200. /**
  201. * Called by JSNI (hooked via {@link #onloadstrategy})
  202. */
  203. private void onSubmitComplete() {
  204. /* Needs to be run dereferred to avoid various browser issues. */
  205. Scheduler.get().scheduleDeferred(new Command() {
  206. @Override
  207. public void execute() {
  208. if (submitted) {
  209. if (client != null) {
  210. if (t != null) {
  211. t.cancel();
  212. }
  213. VConsole.log("VUpload:Submit complete");
  214. client.sendPendingVariableChanges();
  215. }
  216. rebuildPanel();
  217. submitted = false;
  218. enableUpload();
  219. if (!isAttached()) {
  220. /*
  221. * Upload is complete when upload is already abandoned.
  222. */
  223. cleanTargetFrame();
  224. }
  225. }
  226. }
  227. });
  228. }
  229. ScheduledCommand startUploadCmd = new ScheduledCommand() {
  230. @Override
  231. public void execute() {
  232. element.submit();
  233. submitted = true;
  234. disableUpload();
  235. /*
  236. * Visit server a moment after upload has started to see possible
  237. * changes from UploadStarted event. Will be cleared on complete.
  238. *
  239. * Must get the id here as the upload can finish before the timer
  240. * expires and in that case nextUploadId has been updated and is
  241. * wrong.
  242. */
  243. final int thisUploadId = nextUploadId;
  244. t = new Timer() {
  245. @Override
  246. public void run() {
  247. // Only visit the server if the upload has not already
  248. // finished
  249. if (thisUploadId == nextUploadId) {
  250. VConsole.log("Visiting server to see if upload started event changed UI.");
  251. client.updateVariable(paintableId, "pollForStart",
  252. thisUploadId, true);
  253. }
  254. }
  255. };
  256. t.schedule(800);
  257. }
  258. };
  259. /** For internal use only. May be removed or replaced in the future. */
  260. public void submit() {
  261. if (submitted || !enabled) {
  262. VConsole.log("Submit cancelled (disabled or already submitted)");
  263. return;
  264. }
  265. if (fu.getFilename().length() == 0) {
  266. VConsole.log("Submitting empty selection (no file)");
  267. }
  268. // flush possibly pending variable changes, so they will be handled
  269. // before upload
  270. client.sendPendingVariableChanges();
  271. // This is done as deferred because sendPendingVariableChanges is also
  272. // deferred and we want to start the upload only after the changes have
  273. // been sent to the server
  274. Scheduler.get().scheduleDeferred(startUploadCmd);
  275. }
  276. @Override
  277. protected void onAttach() {
  278. super.onAttach();
  279. if (client != null) {
  280. ensureTargetFrame();
  281. }
  282. }
  283. /** For internal use only. May be removed or replaced in the future. */
  284. public void ensureTargetFrame() {
  285. if (synthesizedFrame == null) {
  286. // Attach a hidden IFrame to the form. This is the target iframe to
  287. // which the form will be submitted. We have to create the iframe
  288. // using innerHTML, because setting an iframe's 'name' property
  289. // dynamically doesn't work on most browsers.
  290. DivElement dummy = Document.get().createDivElement();
  291. dummy.setInnerHTML("<iframe src=\"javascript:''\" name='"
  292. + getFrameName()
  293. + "' style='position:absolute;width:0;height:0;border:0'>");
  294. synthesizedFrame = dummy.getFirstChildElement();
  295. Document.get().getBody().appendChild(synthesizedFrame);
  296. element.setTarget(getFrameName());
  297. onloadstrategy.hookEvents(synthesizedFrame, this);
  298. }
  299. }
  300. private String getFrameName() {
  301. return paintableId + "_TGT_FRAME";
  302. }
  303. @Override
  304. protected void onDetach() {
  305. super.onDetach();
  306. if (!submitted) {
  307. cleanTargetFrame();
  308. }
  309. }
  310. private void cleanTargetFrame() {
  311. if (synthesizedFrame != null) {
  312. Document.get().getBody().removeChild(synthesizedFrame);
  313. onloadstrategy.unHookEvents(synthesizedFrame);
  314. synthesizedFrame = null;
  315. }
  316. }
  317. }