I have a non-traditional, image upload button on my company's website. I want to have an automated way to upload an image using this button, but without having to use a tool like AutoIt in order to interact with the file explorer.
Here's a sample of this button's HTML:
<button ng-click="onClick()" ng-disabled="readOnly" accepted-types="image/*" on-files-selected="onFilesSelected" allow-multiple="true" readonly="readonly">Add images</button>
It's a bit different than the usual input element, e.g. <input type="file">, and it's using AngularJS. Since it's not an input element, I don't think I can use Selenium's sendKeys() function to input the image's file location on my machine.
Is there any hack or workaround to uploading the image? I was considering things like overwriting the onClick() function to do read from a specified location (this approach doesn't really seem like it's doable), or possibly intercepting the event that opens the file explorer and trying to hack my way from there, but these are all just unsupported and untested approaches to solving the problem.
Would it be possible to do this in another browser-automation tool, like Microsoft's Playwright?
Use JACOB it provides java native interface where you can use AutoIt functionalities with selenium here is a sample I am using it in most of the places like MSTeams,Slack for Automation[Upload Feature] it does the job.
List of Steps you need to do before jumping to the code:
Step 1:
Download JACOB jar
Step 2:
Register the AutoIt COM libraries e.g regsvr32 AutoItX3_x64.dll
Use these in your code
jacob.jar
AutoItX4Java.jar
jacob-1.18-x64.dll
jacob-1.18-x86.dll
Sample Code:
[This Code Interacts with file explorer]
import com.jacob.com.LibraryLoader;
import autoitx4java.AutoItX;
public class Attachments {
public void uploadAttachments(){
File f = new File("Location");
File[] fil =f.listFiles();
//Upload Button Xpath
WebElement uploadFromComp = driver.findElement(By.xpath("//span[contains(text(),'Upload from my computer')]"));
uploadFromComp.click();
Thread.sleep(5000);
String jacobDllVersionToUse;
if (jvmBitVersion().contains("32")) {
jacobDllVersionToUse = "jacob-1.19-x86.dll";
} else {
jacobDllVersionToUse = "jacob-1.19-x64.dll";
}
File file1 = new File("registerAutoItDll", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file1.getAbsolutePath());
AutoItX x = new AutoItX();
x.winWaitActive("Open");
x.sleep(5000);
x.send(fil[j].getAbsolutePath());
x.send("{ENTER}", false);
}}
I hope it works for you.
It is 100% posible with playwright and it is lot simplier then in the Selenium.
// Select one file
await page.setInputFiles('input#upload', 'myfile.pdf');
// Select multiple files
await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']);
See more on:
https://playwright.dev/docs/input#upload-files
Related
How to set File objects and length property at FileList object where the files are also reflected at FormData object?
I was trying to use the hack described in the link above to insert through code the file I want to upload to an '<input type='file', but I am having trouble to implement it.
I am using the following code as a snippet in Chrome devtools Console Panel:
inp = document.querySelector("input[type=file]");
const dT = new DataTransfer();
dT.items.add(new File(['foo'], 'C:\\Users\\MyUser\\Desktop\\SomeFolder\\MyTestFile.txt'));
inp.files = dT.files;
The input text that should display only the file name shows the full path, and when I press the button to upload the file it return an error saying that the file was not founded.
I already check the path and it is 100% right. I don't know much about javascript, in fact I am using Selenium to do the rest of the automation, but this particular subject looks like can only be achieved with js.
Could anyone help me? Am I mising something or did I misunderstood the hack solution and what I am trying to do is not possible at all?
I have created a file as part of a script on a network drive and i am trying to make it hidden so that if the script is run again it should be able to see the file and act on the information contained within it but i am having trouble doing this. what i have so far is:
function doesRegisterExist(oFs, Date, newFolder) {
dbEcho("doesRegisterExist() triggered");
sExpectedRegisterFile = newFolder+"\\Register.txt"
if(oFs.FileExists(sExpectedRegisterFile)==false){
newFile = oFs.OpenTextFile(sExpectedRegisterFile,8,true)
newFile.close()
newReg = oFs.GetFile(sExpectedRegisterFile)
dbEcho(newReg.Attributes)
newReg.Attributes = newReg.Attributes+2
}
}
Windows Script Host does not actually produce an error here and the script runs throgh to competion. the only guides i have found online i have been attempting to translate from VBscript with limited success.
variables passed to this function are roughly declared as such
var oFs = new ActiveXObject("Scripting.FileSystemObject")
var Date = "29-12-2017"
var newFolder = "\\\\File-Server\\path\\to\\folder"
I know ActiveX is a dirty word to a lot of people and i should be shot for even thinking about using it but it really is a perfect fit for what i am trying to do.
Please help.
sExpectedRegisterFolder resolves to \\\\File-Server\\path\\to\\folder\\Register which is a folder and not a file.
I get an Error: file not found when I wrap the code into a try/catch block.
I tested the code on a text file as well, and there it works.
So you're either using the wrong method if you want to set the folder to hidden.
Or you forgot to include the path to the text if you want to change a file to hidden.
( Edit: Or if Register is the name of the file, add the filetype .txt ? )
If you change GetFile to GetFolder as described in https://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx
the folder will get hidden correctly.
I'm currently porting a nodejs / angular webapp to Windows using nodewebkit. Everything has been working pretty well for now but I'm facing a litle problem when I want the user to download a file.
In order to start the download with the save file Dialog, I use a simple window.open(url) where url can be a link to any kind of files. This line actually do it's job and pop the window dialog for saving a file, but at the same time, a blank node-webkit page appears.
I've been trying to mess around with node-webkit for a while without managing to remove this blank page.
As anyone experienced the same kind of behavior ?
I'll be interested in any lead, I'm not into the js stuff for long so I may have missed something obviouvs.
Have a nice wathever time of the day it is where you live !
a more better solution is found here
Step 1 In your html file, add a Input tag block like below:
<input id="export_file" type="file" nwsaveas style="display:none" nwworkingdir=""/>
Step 2 Add a new function in your javascript file like below:
function saveFile(name,data) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
console.log(this.value); // get your file name
var fs = require('fs');// save it now
fs.writeFile(this.value, data, function(err) {
if(err) {
alert("error"+err);
}
});
}, false);
chooser.click();
}
Step 3 Save your file where ever you like by using saveFile(name,data) function like below:
...
_exportCSV="you data to save";
saveFile('#export_file',_exportCSV);
...
As questioner said to be working:
location.href = url
Is the correct usage.
So similar to ALt-Shift-F in Netbeans, is there a to do this right in the ide in TestComplete? Not sure if this is possible or if anyone can think of a workaround to autoFormat without leaving the TestComplete window.
I'm trying to get the below solution to work with http://jsbeautifier.org/ for javascript / Jscript code in TestComplete.
Thanks
Great question!
There is no built-in function for that. So, we should not expect any solution to be 100% convenient - it is just not a simple task to modify the current script editor contents (if at all possible). So, whatever you do, it will still be some kind of compromise.
In general, the task is three-fold:
Get the current unit code.
Format the code.
Put the code back to the unit.
According to my understanding, items 1 and 3 can be accomplished only by creating a TestComplete plug-in - accessing editors for project nodes is not an easy thing.
UPDATE: silly me! There is a way to access the script editor code - I've updated the below part.
What will help us avoid switching to a different app, are the Script Extensions:
We create a custom Checkpoint in the form of a Script Extension, and install it to TestComplete. As a result, we get a button on the toolbar that we can click to invoke our code.
In the design time action, we call some code that reads the editor contents, then uses external code formatting functionality, and replaces the editor contents with the formatted code.
It would extremely interesting to see the implementations other TestComplete users can suggest! As a start, I am posting a solution that includes using an external web site to format VBScript code (http://www.vbindent.com/). I know that the starter of the post is probably using JScript, but I have not found a JScript formatter yet.
My solution is a simple Script Extension. I can't post a file here, so I will post the code of the two Script Extension files:
Description file:
<!-- Description.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<ScriptExtensionGroup>
<Category Name="Checkpoints">
<ScriptExtension Name="VBScript Code Indent" Author="SmartBear Software" Version="0.1" HomePage="smartbear.com">
<Script Name="VBIndent.js">
<DesignTimeAction Name="Indent Current VBScript Unit" Routine="DesignTimeExecute"/>
</Script>
<Description>
Indents VBScript code in the currently active unit.
</Description>
</ScriptExtension>
</Category>
</ScriptExtensionGroup>
Code file:
// VBIndent.js
function DesignTimeExecute()
{
if (CodeEditor.IsEditorActive)
{
var newCode = IndentVBSCode_Through_VBIndent(CodeEditor.Text);
if (null == newCode)
return;
CodeEditor.Text = newCode;
}
}
function IndentVBSCode_Through_VBIndent(codeToIndent)
{
var URL_VBIndent = "http://www.vbindent.com/?indent";
var httpObj = Sys.OleObject("MSXML2.XMLHTTP");
httpObj.open("POST", URL_VBIndent, false);
httpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpObj.send("thecode=" + escape(codeToIndent));
var responseText = httpObj.responseText;
// Extract the indented code from the response
var rx = /<textarea name=\"thecode\".*?>((.*\n)*?)<\/textarea>/;
matches = rx.exec(responseText);
if (null == matches)
{
return null;
}
codeIndented = matches[1];
return codeIndented;
}
After you create these files, and put them to something like "\Bin\Extensions\ScriptExtensions\VBIndent", and click "File | Install Script Extensions | Reload", you will see a new "Indent Current VBScript Unit" item in the custom checkpoints drop-down button on the Tools toolbar. Clicking the element will format the VBScript code in the currently active editor.
So, this is to give a clear idea of what a solution can look like. Better suggestions are welcome! Share your thoughts!
FYI
I've done. Based on your posts.
JSFormat.tcx
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jcm8wbTJ2dUpZQTQ
To install the extension copy attached file JSFormat.tcx to C:\Program Files (x86)\SmartBear\TestComplete 10\Bin\Extensions\ScriptExtensions
To use view next image:
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jc3RuLXFpTnlCSnc
Regards
How to tag images in the image itself in a web page?
I know Taggify, but... is there other options?
Orkut also does it to tag people faces... How is it done?
Anyone knows any public framework that is able to do it?
See a sample bellow from Taggify:
I know this isn't javascript but C# 3.0 has an API for doing this. The System.Windows.Media.Imaging namespace has a class called BitmapMetadata which can be used to read and write image metadata (which is stored in the image itself). Here is a method for retrieving the metadata for an image given a file path:
public static BitmapMetadata GetMetaData(string path)
{
using (Stream s = new System.IO.FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnDemand);
var frame = decoder.Frames.FirstOrDefault();
if (frame != null)
{
return frame.Metadata as BitmapMetadata;
}
return null;
}
}
The BitmapMetadata class has a property for tags as well as other common image metadata. To save metadata back to the image, you can use the InPlaceBitmapMetadataWriter Class.
There's a map tag in HTML that could be used in conjunction with Javascript to 'tag' different parts of an image.
You can see the details here.
I will re-activate this question and help a bit. Currently the only thing i have found about is http://www.sanisoft.com/downloads/imgnotes-0.2/example.html . A jQuery tagging implementation. If anyone knows about another way please tell us.
;)
You can check out Image.InfoCards (IIC) at http://www.imageinfocards.com . With the IIC meta-data utilities you can add meta-data in very user-friendly groups called "cards".
The supplied utilities (including a Java applet) allow you to tag GIF's, JPEG's and PNG's without changing them visually.
IIC is presently proprietary but there are plans to make it an open protocol in Q1 2009.
The difference between IIC and others like IPTC/DIG35/DublinCore/etc is that it is much more consumer-centric and doesn't require a CS degree to understand and use it...