问题
I'm creating selenium ide tests and now I have problem. I can't write test for uploading a file from local disk.
My dropzone looks like: http://www.dropzonejs.com/examples/simple.html
Can somebody helps me?
回答1:
I ran into the same issue and I found the answer here: How to interact with Dropzone using selenium
I used most of this but I had to create my own method to convert to base64 properly.
public static String convertFileToBase64String(String fileName) throws IOException {
File file = new File(fileName);
int length = (int) file.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[length];
reader.read(bytes, 0, length);
reader.close();
String encodedFile = Base64.getEncoder().encodeToString(bytes);
return encodedFile;
}
Hope this helps!
回答2:
You can use this java code that runs JS script using the convertFileToBase64String method from the answer above. You need to provide 4 params:
- ID for the Dropzone element ("VUIDropzone96326-dropzone" for example)
- New name for the file you are uploading (sometimes the server expect to specific name)
- Path to file you are uploading
- base64IFile string you have got from convertFileToBase64String merhod
This is the complete solution:
String id = "Put here the ID of the Dropzone element"
String fileName = "Put here desired file name";
String base64IFile = convertFileToBase64String(filePath);
((JavascriptExecutor) driver).executeScript("var myZone = Dropzone.forElement('#" + id + "');" +
"base64Image = '" + base64IFile + "';" +
"function base64toBlob(b64Data, contentType, sliceSize) { \n" +
" contentType = contentType || '';\n" +
" sliceSize = sliceSize || 512;\n" +
"\n" +
" var byteCharacters = atob(b64Data);\n" +
" var byteArrays = [];\n" +
"\n" +
" for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n" +
" var slice = byteCharacters.slice(offset, offset + sliceSize);\n" +
"\n" +
" var byteNumbers = new Array(slice.length);\n" +
" for (var i = 0; i < slice.length; i++) {\n" +
" byteNumbers[i] = slice.charCodeAt(i);\n" +
" }\n" +
"\n" +
" var byteArray = new Uint8Array(byteNumbers);\n" +
"\n" +
" byteArrays.push(byteArray);\n" +
" }\n" +
"\n" +
" var blob = new Blob(byteArrays, {type: contentType});\n" +
" return blob;\n" +
"}" +
"var blob = base64toBlob(base64Image, 'image / png');" +
"blob.name = '" + fileName + "';" +
"myZone.addFile(blob); "
);
回答3:
Usually, there is a hidden form input
<input type="file" multiple="multiple" class="dz-hidden-input" accept="image/jpg,image/jpeg style="visibility: hidden>
So you can simply communicate with that hidden element
来源:https://stackoverflow.com/questions/34769506/upload-file-with-selenium-ide-to-the-dropzone-js