You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VUpload.java 15KB

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