I'm using Puppeteer Sharp to test my web app. My web app has a button that triggers an <input type="file"> to let the user select a CSV file to upload.
How do I use that to upload a file when testing via Puppeteer Sharp? Just clicking the button isn't enough, because I need to give the browse-for-file dialog a path to the file.
You can use Page.WaitForFileChooserAsync to interact with the file chooser. The important thing to remember is you need to have the file chooser ready before you click the <input type="file">.
For example:
var fileChooserDialogTask = page.WaitForFileChooserAsync(); // Do not await here
await Task.WhenAll(fileChooserDialogTask, page.ClickAsync("input[type='file']"));
var fileChooser = await fileChooserDialogTask;
await fileChooser.AcceptAsync(pathToFile);
If you try to click the <input type="file"> before you've called WaitForFileChooserAsync, you'll be stuck with the modal file chooser dialog waiting for you to do something.
Related
Hi is there any way to get link for file, when I click on Download button browser start to download file.
I have following html button tag.
<button type="button" ng-click="vm.handleClick(vm.item[1])">Download</button>
When I use this it only download file, is there any way to get link from ng-click event?
executor.ExecuteScript("arguments[0].click()", webElement);
I'm using Geckofx in my winform application to fill a form on a website. One of the controls is a button "Choose Files" which lets you select and upload a local file. I want to automate this process by doing this fully via code.
I managed to click this button via code:
Gecko.DOM.GeckoButtonElement button = new Gecko.DOM.GeckoButtonElement(doc.GetElementsByClassName("choose_files_btn").First().DomObject);
button.Click();
As a result a file dialog is opened automatically but I want to automate the file choosing part and clicking 'OK' as well. I tried inspecting the webpage to find whether I could assign the path of my local file to some Gecko element but couldn't find anything of this sort.
I also thought about handling the event of opening the file dialog but couldn't find any event handler in Gecko. I found Gecko.LauncherDialog.Download event handler which is used for handling downloading a file using Geckofx browser. But there's no such event handler for uploading files using Geckofx browser, if there is and I missed it, do tell.
Maybe I can use an event handler not from Gecko but from System, if I write an event handler which will catch every open file dialog event but I don't know whether that's even possible.
Here is a solution, to upload without showing the file upload dialog:
GeckoHtmlElement el = webbrowser.DomDocument.GetElementsByTagName("input").FirstOrDefault(elz => elz.GetAttribute("type") == "file"); //inpout type file element
var fileNames = new IntPtr[1];
fileNames[0] = new Gecko.CustomMarshalers.WStringMarshaler().MarshalManagedToNative(file); //file = path to file you want to upload
var domInput = Xpcom.QueryInterface<nsIDOMHTMLInputElement>(el.DOMHtmlElement);
domInput.MozSetFileNameArray(fileNames, (uint)fileNames.Length);
Marshal.ReleaseComObject(domInput);
DomEventArgs ev = webbrowser.Document.CreateEvent("HTMLEvents");
var webEvent = new Event(webbrowser.Window.DomWindow, ev.DomEvent as nsISupports);
webEvent.InitEvent("change", true, true);
el.GetEventTarget().DispatchEvent(ev);
new Gecko.CustomMarshalers.WStringMarshaler().CleanUpNativeData(fileNames[0]); //delete everything
I am trying to upload files into a website using selenium which when Clicked on Choose file opens a Native windows, so for this purpose I have been using AutoIT which seems not very reliable when I go for parallel execution.
Since I am using Selenium with C# I thought of finding some solution through which I can handle that Native window but I am unable to find any solution please can anybody tell me some reliable way to do this particular automation.
This worked for me so hopefully it'll work for you. I use it in an extension method here, but you can use as/in a normal method. So this uses C# libraries to enter the path in the dialog and presses enter when done.
string idPath = "C:/text.txt"; //Path to the file you are trying to upload
var button = driver.FindElement(By.Id("blah"));
button.Click()
driver.WaitOnAPage(1); //simple wait method
SendKeys.SendWait(#idPath); //this code sends the path to the file upload dialog
CommonMethods.WaitOnAPage(1);//simple wait method
SendKeys.SendWait(#"{Enter}"); //simulates pressing enter button
There are multiple ways to go on this:
IWebElement element = driver.FindElement(By.Id("your_path_to_file_here"));
element.SendKeys("C:\\Some_Folder\\MyFile.txt");
Using IJavaScriptExecutor:
IWebElement element = driver.FindElement(By.Id("your_path_to_file_here"));
string script = "arguments[0].value='" + "C:\\\\temp\\\\file.txt" + "';";
((IJavascriptExecutor)driver).executeScript(script, element);
Both options insert the text directly in your file path input and afterwards you can just click the Upload button.
Background:
I am working on an undergrad research project for my CS department. The project is a website for the biology department and a key feature is that the biology students are able to upload their own .xml files and then a *model is built for them on the server side using Matlab.
The front end is in an ASP.NET, javascript and C# environment. My little association with this project is all the knowledge I have of these systems, tools and languages.
Question:
The .xml files I mentioned earlier can take hours to upload and build. My professor wants the user to be able to continue on with the page using models that are already completed while the new model is sent to the background and the user receives an email when it is completed. I've found material for sending the email, but not for continuing with the page.
I heard something about using AJAX to load a page?
Place a file upload control on your page
<asp:FileUpload ID="FileUpload1" runat="server"/>
Build an http handler to handle the file upload:
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpPostedFile fileToUpload = context.Request.Files["Filedata"];
string pathToSave = HttpContext.Current.Server.MapPath("~/Files/")
+ fileToUpload.FileName;
fileToUpload.SaveAs(pathToSave);
//Process file
}
public bool IsReusable {
get {
return false;
}
}
}
Take a look if you can integrate an upload plugin like uploadify into the project(needs jQuery).
<script type = "text/javascript">
$(document).ready(function()
{
$("#<%=FileUpload1.ClientID %>").uploadify(
{
'swf': 'Scripts/uploadify.swf',
'uploader': 'Handler.ashx',
'auto': true,
'buttonText': 'Select File(s)'
});
});
</script>
If you cannot do this, you need to understand how ajax works
Ajax normally uses XMLHttpRequest, which does not allow you encode and send local files to a server.
You could, either use a Flash swf to handle the uploading on the same page, or to use a form that has a target of an invisible 1x1 iframe.
I found the code posted on this blog about file uploads in asp.net
I think having a small i-frame open up, which will actually do the upload, will let your current page continue working.
So on your current page, you ask for file location and file name and all, then open a new page in an i-frame. Let that i-frame know the source file/folder, destination file/folder, and let it work in the background. So now your current page is free to continue its work.
Hope that helps.
Use a headless Java Upload Applet.
Load the file transfer applet in an iFrame, let the user initiate the file transfer and when a user wants to browse the rest of the website, just don't reload the iFrame containing the Java Applet (which will be uploading the file). After the transfer is complete, do a JAvaScript call to close the iframe.
The following example uses a Java Applet by FileCatalyst, but the idea will be practically with any other Java FTP Applet or ActiveX
<script>
var browsePath = "";
function browseAndAdd() {
browsePath = document.FileCatalyst.browseLive(true);
}
function upload() {
document.FileCatalyst.uploadLive();
}
function clearQueue() {
document.FileCatalyst.clearQueue();
}
</script>
<!--Uses onClick for demonstration only-->
<form id="uploadform">
<!--Launch a browse dialog and add the selected file to the queue-->
<input type=button onClick="javascript:browseAndAdd();" value="Browse and Add to Queue" />
<!-- Force upload of whatever is currently found in the transfer queue -->
<input type=button onClick="javascript:upload();" value="Upload">
<!-- Clear transfer queue (can be called only if no transfers are in progress) -->
<input type=button onClick="javascript:clearQueue();" value="Clear Queue">
</form>
Apologies for lack of indentation, I find the stackoverflow markup for inserting code snipets not very user friendly.
You need to set up somekind of asynchronous processing ideally. Personally I like to use Celery and RabbitMQ for my async and messaging.
I have the exe file of micromedia flash player. I am able to run this file from the .net application by using the following code
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("peopledisplay.exe");
//System.Diagnostics.Process.Start("iexplorer.exe", "peopledisplay.exe");
}
This code launches the micromedia flash file after clicking the button. I want this file to be launched in the internet explore after clicking the button. How to do this ? Can you please provide me any code or link through which I can resolve the above issue ?
Try this:
System.Diagnostics.Process.Start(#"\"C:\Program Files (x86)\Internet Explorer\iexplore.exe\" \"[path to my file]\"");
you need to specify the path to the flash file on the command line to IE. Make sure you enclose the path with quotes. Of course this is no guarantee that IE will actually be able to run the file, you may find that security restrictions (zone rules, group policy) prevent that.
What you do in this code is tell the server to open the executable, not the browser client. You'd need some JavaScript like the following, but that will probably only work in Internet Explorer, and only if the user explicitly sets the permissions in the IE options window.
<script>
function go() {
w = new ActiveXObject("WScript.Shell");
w.run('peopledisplay.exe');
return true;
}
</script>
<form>
Run Notepad (Window with explorer only)
<input type="button" value="Go"
onClick="return go()">
</form>