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 14KB

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