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

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