Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

VUpload.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright 2000-2016 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.Element;
  23. import com.google.gwt.dom.client.FormElement;
  24. import com.google.gwt.user.client.Event;
  25. import com.google.gwt.user.client.Timer;
  26. import com.google.gwt.user.client.ui.FileUpload;
  27. import com.google.gwt.user.client.ui.FlowPanel;
  28. import com.google.gwt.user.client.ui.FormPanel;
  29. import com.google.gwt.user.client.ui.Hidden;
  30. import com.google.gwt.user.client.ui.Panel;
  31. import com.google.gwt.user.client.ui.SimplePanel;
  32. import com.vaadin.client.ApplicationConnection;
  33. import com.vaadin.client.BrowserInfo;
  34. import com.vaadin.client.ConnectorMap;
  35. import com.vaadin.client.StyleConstants;
  36. import com.vaadin.client.VConsole;
  37. import com.vaadin.client.ui.upload.UploadConnector;
  38. import com.vaadin.client.ui.upload.UploadIFrameOnloadStrategy;
  39. import com.vaadin.shared.ui.upload.UploadServerRpc;
  40. /**
  41. *
  42. * Note, we are not using GWT FormPanel as we want to listen submitcomplete
  43. * events even though the upload component is already detached.
  44. *
  45. * @author Vaadin Ltd
  46. *
  47. */
  48. public class VUpload extends SimplePanel {
  49. private final class VFileUpload extends FileUpload {
  50. @Override
  51. public void onBrowserEvent(Event event) {
  52. super.onBrowserEvent(event);
  53. if (event.getTypeInt() == Event.ONCHANGE) {
  54. if (isImmediateMode() && fu.getFilename() != null
  55. && !fu.getFilename().isEmpty()) {
  56. submit();
  57. }
  58. } else if (BrowserInfo.get().isIE()
  59. && event.getTypeInt() == Event.ONFOCUS) {
  60. // IE and user has clicked on hidden textarea part of upload
  61. // field. Manually open file selector, other browsers do it by
  62. // default.
  63. fireNativeClick(fu.getElement());
  64. // also remove focus to enable hack if user presses cancel
  65. // button
  66. fireNativeBlur(fu.getElement());
  67. }
  68. }
  69. }
  70. public static final String CLASSNAME = "v-upload";
  71. /**
  72. * FileUpload component that opens native OS dialog to select file.
  73. * <p>
  74. * For internal use only. May be removed or replaced in the future.
  75. */
  76. public FileUpload fu = new VFileUpload();
  77. Panel panel = new FlowPanel();
  78. UploadIFrameOnloadStrategy onloadstrategy = GWT
  79. .create(UploadIFrameOnloadStrategy.class);
  80. /** For internal use only. May be removed or replaced in the future. */
  81. public ApplicationConnection client;
  82. /** For internal use only. May be removed or replaced in the future. */
  83. public String paintableId;
  84. /**
  85. * Button that initiates uploading.
  86. * <p>
  87. * For internal use only. May be removed or replaced in the future.
  88. */
  89. public final VButton submitButton;
  90. /**
  91. * When expecting big files, programmer may initiate some UI changes when
  92. * uploading the file starts. Bit after submitting file we'll visit the
  93. * server to check possible changes.
  94. * <p>
  95. * For internal use only. May be removed or replaced in the future.
  96. */
  97. public Timer t;
  98. /**
  99. * some browsers tries to send form twice if submit is called in button
  100. * click handler, some don't submit at all without it, so we need to track
  101. * if form is already being submitted
  102. */
  103. private boolean submitted = false;
  104. private boolean enabled = true;
  105. private boolean immediateMode;
  106. private Hidden maxfilesize = new Hidden();
  107. /** For internal use only. May be removed or replaced in the future. */
  108. public FormElement element;
  109. private com.google.gwt.dom.client.Element synthesizedFrame;
  110. /** For internal use only. May be removed or replaced in the future. */
  111. public int nextUploadId;
  112. public VUpload() {
  113. super(com.google.gwt.dom.client.Document.get().createFormElement());
  114. element = getElement().cast();
  115. setEncoding(getElement(), FormPanel.ENCODING_MULTIPART);
  116. element.setMethod(FormPanel.METHOD_POST);
  117. setWidget(panel);
  118. panel.add(maxfilesize);
  119. panel.add(fu);
  120. submitButton = new VButton();
  121. submitButton.addClickHandler(event -> {
  122. if (isImmediateMode()) {
  123. // fire click on upload (e.g. focused button and hit space)
  124. fireNativeClick(fu.getElement());
  125. } else {
  126. submit();
  127. }
  128. });
  129. panel.add(submitButton);
  130. setStyleName(CLASSNAME);
  131. }
  132. private static native void setEncoding(Element form, String encoding)
  133. /*-{
  134. form.enctype = encoding;
  135. }-*/;
  136. /**
  137. * Sets the upload in immediate mode.
  138. *
  139. * @param immediateMode
  140. * {@code true} for immediate mode, {@code false} for
  141. * non-immediate mode
  142. */
  143. public void setImmediateMode(boolean immediateMode) {
  144. if (this.immediateMode != immediateMode) {
  145. this.immediateMode = immediateMode;
  146. if (immediateMode) {
  147. fu.sinkEvents(Event.ONCHANGE);
  148. fu.sinkEvents(Event.ONFOCUS);
  149. } else {
  150. fu.unsinkEvents(Event.ONCHANGE);
  151. fu.unsinkEvents(Event.ONFOCUS);
  152. }
  153. }
  154. setStyleName(getElement(), CLASSNAME + "-immediate", immediateMode);
  155. }
  156. /**
  157. * Returns whether this component is in immediate mode or not.
  158. *
  159. * @return {@code true} for immediate mode, {@code false} for not
  160. */
  161. public boolean isImmediateMode() {
  162. return immediateMode;
  163. }
  164. private static native void fireNativeClick(Element element)
  165. /*-{
  166. element.click();
  167. }-*/;
  168. private static native void fireNativeBlur(Element element)
  169. /*-{
  170. element.blur();
  171. }-*/;
  172. /** For internal use only. May be removed or replaced in the future. */
  173. public void disableUpload() {
  174. setEnabledForSubmitButton(false);
  175. if (!submitted) {
  176. // Cannot disable the fileupload while submitting or the file won't
  177. // be submitted at all
  178. fu.getElement().setPropertyBoolean("disabled", true);
  179. }
  180. enabled = false;
  181. }
  182. /** For internal use only. May be removed or replaced in the future. */
  183. public void enableUpload() {
  184. setEnabledForSubmitButton(true);
  185. fu.getElement().setPropertyBoolean("disabled", false);
  186. enabled = true;
  187. if (submitted) {
  188. /*
  189. * An old request is still in progress (most likely cancelled),
  190. * ditching that target frame to make it possible to send a new
  191. * file. A new target frame is created later."
  192. */
  193. cleanTargetFrame();
  194. submitted = false;
  195. }
  196. }
  197. private void setEnabledForSubmitButton(boolean enabled) {
  198. submitButton.setEnabled(enabled);
  199. submitButton.setStyleName(StyleConstants.DISABLED, !enabled);
  200. }
  201. /**
  202. * Re-creates file input field and populates panel. This is needed as we
  203. * want to clear existing values from our current file input field.
  204. */
  205. private void rebuildPanel() {
  206. panel.remove(submitButton);
  207. panel.remove(fu);
  208. fu = new VFileUpload();
  209. fu.setName(paintableId + "_file");
  210. fu.getElement().setPropertyBoolean("disabled", !enabled);
  211. panel.add(fu);
  212. panel.add(submitButton);
  213. if (isImmediateMode()) {
  214. fu.sinkEvents(Event.ONCHANGE);
  215. }
  216. }
  217. /**
  218. * Called by JSNI (hooked via {@link #onloadstrategy})
  219. */
  220. private void onSubmitComplete() {
  221. /* Needs to be run dereferred to avoid various browser issues. */
  222. Scheduler.get().scheduleDeferred(() -> {
  223. if (submitted) {
  224. if (client != null) {
  225. if (t != null) {
  226. t.cancel();
  227. }
  228. VConsole.log("VUpload:Submit complete");
  229. if (isAttached()) {
  230. // no need to call poll() if component is already
  231. // detached #8728
  232. ((UploadConnector) ConnectorMap.get(client)
  233. .getConnector(VUpload.this))
  234. .getRpcProxy(UploadServerRpc.class)
  235. .poll();
  236. }
  237. }
  238. rebuildPanel();
  239. submitted = false;
  240. enableUpload();
  241. if (!isAttached()) {
  242. /*
  243. * Upload is complete when upload is already abandoned.
  244. */
  245. cleanTargetFrame();
  246. }
  247. }
  248. });
  249. }
  250. ScheduledCommand startUploadCmd = () -> {
  251. element.submit();
  252. submitted = true;
  253. disableUpload();
  254. /*
  255. * Visit server a moment after upload has started to see possible
  256. * changes from UploadStarted event. Will be cleared on complete.
  257. *
  258. * Must get the id here as the upload can finish before the timer
  259. * expires and in that case nextUploadId has been updated and is wrong.
  260. */
  261. final int thisUploadId = nextUploadId;
  262. t = new Timer() {
  263. @Override
  264. public void run() {
  265. // Only visit the server if the upload has not already
  266. // finished
  267. if (thisUploadId == nextUploadId) {
  268. VConsole.log(
  269. "Visiting server to see if upload started event changed UI.");
  270. client.updateVariable(paintableId, "pollForStart",
  271. thisUploadId, true);
  272. }
  273. }
  274. };
  275. t.schedule(800);
  276. };
  277. /** For internal use only. May be removed or replaced in the future. */
  278. public void submit() {
  279. if (submitted || !enabled) {
  280. VConsole.log("Submit cancelled (disabled or already submitted)");
  281. return;
  282. }
  283. if (fu.getFilename().isEmpty()) {
  284. VConsole.log("Submitting empty selection (no file)");
  285. }
  286. // flush possibly pending variable changes, so they will be handled
  287. // before upload
  288. client.sendPendingVariableChanges();
  289. // This is done as deferred because sendPendingVariableChanges is also
  290. // deferred and we want to start the upload only after the changes have
  291. // been sent to the server
  292. Scheduler.get().scheduleDeferred(startUploadCmd);
  293. }
  294. /** For internal use only. May be removed or replaced in the future. */
  295. public void disableTitle(boolean disable) {
  296. if (disable) {
  297. // Disable title attribute for upload element.
  298. if (BrowserInfo.get().isChrome()) {
  299. // In Chrome title has to be set to " " to make it invisible
  300. fu.setTitle(" ");
  301. } else if (BrowserInfo.get().isFirefox()) {
  302. // In FF title has to be set to empty string to make it
  303. // invisible
  304. // Method setTitle removes title attribute when it's an empty
  305. // string, so setAttribute() should be used here
  306. fu.getElement().setAttribute("title", "");
  307. }
  308. // For other browsers absent title doesn't show default tooltip for
  309. // input element
  310. } else {
  311. fu.setTitle(null);
  312. }
  313. }
  314. @Override
  315. protected void onAttach() {
  316. super.onAttach();
  317. if (client != null) {
  318. ensureTargetFrame();
  319. }
  320. }
  321. /** For internal use only. May be removed or replaced in the future. */
  322. public void ensureTargetFrame() {
  323. if (synthesizedFrame == null) {
  324. // Attach a hidden IFrame to the form. This is the target iframe to
  325. // which the form will be submitted. We have to create the iframe
  326. // using innerHTML, because setting an iframe's 'name' property
  327. // dynamically doesn't work on most browsers.
  328. DivElement dummy = Document.get().createDivElement();
  329. dummy.setInnerHTML("<iframe src=\"javascript:''\" name='"
  330. + getFrameName()
  331. + "' style='position:absolute;width:0;height:0;border:0'>");
  332. synthesizedFrame = dummy.getFirstChildElement();
  333. Document.get().getBody().appendChild(synthesizedFrame);
  334. element.setTarget(getFrameName());
  335. onloadstrategy.hookEvents(synthesizedFrame, this);
  336. }
  337. }
  338. private String getFrameName() {
  339. return paintableId + "_TGT_FRAME";
  340. }
  341. @Override
  342. protected void onDetach() {
  343. super.onDetach();
  344. if (!submitted) {
  345. cleanTargetFrame();
  346. }
  347. }
  348. private void cleanTargetFrame() {
  349. if (synthesizedFrame != null) {
  350. Document.get().getBody().removeChild(synthesizedFrame);
  351. onloadstrategy.unHookEvents(synthesizedFrame);
  352. synthesizedFrame = null;
  353. }
  354. }
  355. }