1212import org .openqa .selenium .WebDriver ;
1313import org .openqa .selenium .htmlunit .HtmlUnitDriver ;
1414import org .openqa .selenium .ie .InternetExplorerDriver ;
15- import sun .plugin .dom .exception .BrowserNotSupportedException ;
1615
1716import java .io .File ;
1817import java .io .IOException ;
19- import java .io .UnsupportedEncodingException ;
2018import java .net .URL ;
21- import java .nio .charset .Charset ;
2219
2320/**
2421 * Created by rac on 08.06.14.
@@ -89,7 +86,7 @@ private String getDownloadJsCallScript(URL url) {
8986 * @param url
9087 * @return raw data
9188 */
92- public byte [] getFileFromUrl (URL url ) {
89+ public FileData getFileFromUrlRaw (URL url ) {
9390 String scriptCollection ;
9491 if (js instanceof InternetExplorerDriver ) {
9592 scriptCollection = ieHackTestJs + ieHackJs + base64Js + dlHelperJs + getDownloadJsCallScript (url );
@@ -99,8 +96,14 @@ public byte[] getFileFromUrl(URL url) {
9996 } else {
10097 scriptCollection = ieHackTestJs + base64Js + dlHelperJs + getDownloadJsCallScript (url );
10198 }
102- String encodedContent = (String ) js .executeScript (scriptCollection );
103- return Base64 .decodeBase64 (encodedContent );
99+ String jsRetVal = (String ) js .executeScript (scriptCollection );
100+ String [] jsRetArr = jsRetVal .split (":contentstarts:" , 2 );
101+ String encodedContent = jsRetArr [1 ];
102+ String fileName = jsRetArr [0 ];
103+ if (fileName .equals ("" )) {
104+ fileName = url .getFile ().replaceAll ("/" , "" );
105+ }
106+ return new FileData (fileName , Base64 .decodeBase64 (encodedContent ));
104107 }
105108
106109 /**
@@ -113,9 +116,25 @@ public byte[] getFileFromUrl(URL url) {
113116 * @throws IOException
114117 */
115118 public File getFileFromUrl (URL url , File outputFile ) throws IOException {
116- byte [] content = getFileFromUrl (url );
119+ byte [] content = getFileFromUrlRaw (url ). getData ( );
117120 FileUtils .writeByteArrayToFile (outputFile , content );
118121 return outputFile ;
119122 }
120123
124+ /**
125+ * Executes XHR request trough JavaScript to download the given file in the context of the current WebDriver
126+ * session. This method returns a tmp file and takes a guessed filename
127+ *
128+ * @param url
129+ * @return outpuFile
130+ * @throws IOException
131+ */
132+ public File getFileFromUrl (URL url ) throws IOException {
133+ FileData fd = getFileFromUrlRaw (url );
134+ byte [] content = fd .getData ();
135+ File tmpFile = File .createTempFile ("" , fd .getGuessedFilename ());
136+ FileUtils .writeByteArrayToFile (tmpFile , content );
137+ return tmpFile ;
138+ }
139+
121140}
0 commit comments