I have to select one of the several values of type radio button using #FindBy.
Here is my html code that I need to automate.
I tried giving #FindBy(how=How.CSS,using= "[type='radio']" and value)
But I have to pass in the value dynamically. ie. Chose BlueSkies or Pangea airlines.What is the best way to write it.Will #FindBy return a list of WebElements and can I work on it like that. Please help.
<input type="radio" name="outFlight" value="Blue Skies Airlines$361$271$7:10"/>
</td>
<td class="data_left" align="LEFT" bgcolor="CCCCCC">
<font size="-1" face="ARIAL">
<b>Blue Skies Airlines 361</b>
</font>
</td>
<td class="data_center_mono" align="CENTER" valign="TOP" bgcolor="CCCCCC">
<font size="-1" face="ARIAL">7:10</font>
<br/>
</td>
<td class="data_center" align="CENTER" bgcolor="CCCCCC" nowrap="">
<font size="-1" face="ARIAL">non-stop</font>
</td>
</tr>
<tr>
<td class="data_verb_xcols" valign="top" bgcolor="#FFFFFF" colspan="4">
</tr>
<tr>
<td class="frame_action_xrows" rowspan="2" align="CENTER" bgcolor="#FFCC00" valign="CENTER">
<input type="radio" name="outFlight" value="Pangea Airlines$362$274$9:17"/>
</td>
<td class="data_left" align="LEFT" bgcolor="CCCCCC">
<font size="-1" face="ARIAL">
<b>Pangaea Airlines 362</b>
</font>
</td>
The value in #FindBy can't be dynamic. You can split it to two
#FindBy(how = How.CSS, using = "[value*='Blue Skies Airlines']")
private WebElement blueSkyesRadioButton;
#FindBy(how = How.CSS, using = "[value*='Pangea Airlines']")
private WebElement pangeaAirlinesRadioButton;
Or to insert them both to list and work with indexes
#FindBy(how = How.CSS, using = "[type='radio']")
private List<WebElement> radioButtons;
#FindBy(how = How.CSS, using = "[type='radio']")
private List<WebElement> radioButtons;
Some more explanation supporting the solution give by #Guy, you can write an method to select radio dynamically. For an example
public void selectRadio(String airlineName){
for(WebElement radio : radioButtons){
if(radio.getAttribute("value").contains(airlineName)
radio.click();
}
}
You can use iterator if you wish. You just need to call this method by page object passing the airlineName as an argument.
Code trials:
package modules;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.support.ui.Select;
public class PostUpdating {
public void Execute()
{
WebElement w = LaunchApplication.driver.findElement(By.id("whats-new"));
w.sendKeys("/C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
Select sel = new Select(LaunchApplication.driver.findElement(By.id("rtSelectPrivacy")));
sel.selectByVisibleText("Public");
Select sel1 = new Select(LaunchApplication.driver.findElement(By.id("whats-new-post-in")));
sel1.selectByVisibleText("My Profile");
LaunchApplication.driver.findElement(By.id("aw-whats-new-submit")).click();
}
}
The html
<div id="whats-new-textarea" style="position: relative;">
<textarea id="whats-new" class="bp-suggestions linkBox" rows="10" cols="50" name="whats-new" style="display: inline-block; height: 50px;"></textarea>
<div id="rtm-drop-files-title">Drop files here</div>
<div class="rtmp-url-scrapper-container">
<img class="rtmp-url-scrapper-loading" src="http://demo.rtcamp.com/rtmedia/wp-content/plugins/buddypress-media/app/assets/admin/img/boxspinner.gif">
<table id="rtmp-url-scrapper" style="display: none;">
<tbody>
<tr>
<td>
<table id="rtmp-url-scrapper-img-holder">
<tbody>
<tr>
<td style="height:100px; overflow:hidden;" colspan="2">
<div id="rtmp-url-scrapper-img">
<img src="">
</div>
</td>
</tr>
<tr>
<td id="" style="width:50%; text-align:right;">
<input id="rtmp-url-prevPicButton" type="button" value="<">
</td>
<td id="" style="width:50%; text-align:left;">
<input id="rtmp-url-nextPicButton" type="button" value=">">
</td>
</tr>
<tr>
<td colspan="2">
<div id="rtmp-url-scrapper-img-count"></div>
</td>
</tr>
</tbody>
</table>
</td>
<td>
I want to insert a image into my text box but when I use Sendkeys and gave the path from my computer but instead of sending the image it is sending the path only into my text box.Also there is a button in my webpage for uploading the picture but when I clicked on button windows dialoge box open. So selenium can't deal with Windows GUI.So Any help how to do this?
drv.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")
To insert an image into the text box you need to send the filename along with the absolute path as a character sequence to the element inducing WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("textarea.bp-suggestions.linkBox#whats-new"))).sendKeys("/C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//textarea[#class='bp-suggestions linkBox' and #id='whats-new']"))).sendKeys("/C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
I have an element that looks like combo box ( DevEx control ). Its Tag is input and not Select. Hence Select command does not work. I can locate that element and when send a click command, it opens the list. However, I am not able to select any Value from it.
Code snippet using firebug is as follows:
input id="ctl00_MainContent_tbc_UserRights_tbpnl_UserInfo_ddl_Company_I" class="dxeEditArea dxeEditAreaSys" type="text" style="cursor:default;" onchange="aspxETextChanged('ctl00_MainContent_tbc_UserRights_tbpnl_UserInfo_ddl_Company')" readonly="readonly" name="ctl00$MainContent$tbc_UserRights$tbpnl_UserInfo$ddl_Company" autocomplete="off" tabindex="14" onfocus="aspxEGotFocus('ctl00_MainContent_tbc_UserRights_tbpnl_UserInfo_ddl_Company')" onblur="aspxELostFocus('ctl00_MainContent_tbc_UserRights_tbpnl_UserInfo_ddl_Company'
Selenium Code is as Follows
WebElement companydropdown = driver.findElement(By.id("ctl00_MainContent_tbc_UserRights_tbpnl_UserInfo_ddl_Company_I")); Select Clickthis1 = new Select (companydropdown); clickThis.selectByVisibleText("Multi National Retail Group");
error is as follows
Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input" Build info: version: '2.45.0', revision: '32a636c', time: '2015-03-05 22:01:35' System info: host: 'ct-113', ip: '172.24.1.248', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.8.0_45' Driver info: driver.version: unknown at org.openqa.selenium.support.ui.Select.(Select.java:46) at MyPackage.MyClass.main(MyClass``.java:113)
Your drop down list is being simulated by JavaScript. It's probably a DIV (or maybe a SELECT or TABLE) after clicking the input, so you will need to locate that new element after clicking the input.
There's no built in command. You may need to FindElement(By.CssPath("table[id*=ddl_Company] td:contains(Default Company)")) and click it
Please see below code snippet, I have written in c# but you can take this reference for any language.
Basic idea is to design logic to select elements from dropdown by using FindElement and FindElements.
Extension Method of IWebDriver
public static class SeleniumExtension
{
public static void SelectDropDownByText(this IWebDriver driver, string clickId, string tableId, string visibleText)
{
//Click on dropdown element to see dropdown options
driver.FindElement(By.Id(clickId)).Click();
//Get all rows from the table(dropdown options table) by tableId
var trElements = driver.FindElement(By.Id(tableId)).FindElements(By.CssSelector("tr"));1
//Go to row by row
foreach(var trElement in trElements)
{
//Select celll(td) of the row
var tdElement = trElement.FindElement(By.CssSelector("td"));
//Scoll to that td so we can select the td
Actions actions = new Actions(driver);
actions.MoveToElement(tdElement);
actions.Perform();
//CHeck td text if td text is equal to given text then click that td
if (tdElement.Text.Trim() == visibleText.Trim())
{
//Select td/dropdown option
tdElement.Click();
break;
}
}
}
}
Limitations:-
The dropdown items should not have duplicate text elements
Just found one way to select it by visible text, not by Id or Value
Code example :
Web page source code
<td width="55%" valign="top" align="left">
<table class="dxeButtonEdit inputBox" cellspacing="1" cellpadding="0" id="EnterOrderModel.reportstoprofs" style="width:150px;">
<tbody>
<tr>
<td style="display:none;"><input id="EnterOrderModel.reportstoprofs_VI" name="EnterOrderModel.reportstoprofs_VI" type="hidden" value="AAAA"></td>
<td class="dxic" onmousedown="return aspxDDDropDown('EnterOrderModel.reportstoprofs', event)" style="width:100%;padding-left:1px;padding-right:1px;padding-top:1px;padding-bottom:1px;"><input class="dxeEditArea dxeEditAreaSys" id="EnterOrderModel.reportstoprofs_I" name="EnterOrderModel.reportstoprofs" onfocus="aspxEGotFocus('EnterOrderModel.reportstoprofs')" onblur="aspxELostFocus('EnterOrderModel.reportstoprofs')" onchange="aspxETextChanged('EnterOrderModel.reportstoprofs')" onkeydown="aspxEKeyDown('EnterOrderModel.reportstoprofs', event)" value="Parmnad(AAAA)" type="text" style="height:15px;" autocomplete="off"></td>
<td id="EnterOrderModel.reportstoprofs_B-1" class="dxeButtonEditButton" onmousedown="return aspxDDDropDown('EnterOrderModel.reportstoprofs', event)" style="-khtml-user-select:none;">
<table class="dxbebt" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border-collapse:separate;">
<tbody>
<tr>
<td class="dx"><img id="EnterOrderModel.reportstoprofs_B-1Img" class="dxEditors_edtDropDown" src="/DXR.axd?r=1_5-7rgYm" alt="v"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<input type="hidden" id="EnterOrderModel.reportstoprofs_DDDWS" name="EnterOrderModel.reportstoprofs_DDDWS" value="0:0:-1:-10000:-10000:0:-10000:-10000:1">
<div id="EnterOrderModel.reportstoprofs_DDD_PW-1" style="position:absolute;left:0px;top:0px;z-index:10000;visibility:hidden;display:none;">
<table id="EnterOrderModel.reportstoprofs_DDD_PWST-1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border-collapse:separate;position:relative;">
<tbody>
<tr>
<td onmousedown="aspxPWMDown(event,'EnterOrderModel.reportstoprofs_DDD',-1,false)" style="width:200px;cursor:default;">
<table id="EnterOrderModel.reportstoprofs_DDD_CLW-1" cellspacing="0" cellpadding="0" style="width:200px;border-collapse:collapse;border-collapse:separate;">
<tbody>
<tr>
<td id="EnterOrderModel.reportstoprofs_DDD_PWC-1" style="height:100%;">
<div id="EnterOrderModel.reportstoprofs_DDD_CSD-1">
<input type="hidden" id="EnterOrderModel.reportstoprofs_DDD_LDeletedItems" name="EnterOrderModel.reportstoprofs_DDD_LDeletedItems" value=""><input type="hidden" id="EnterOrderModel.reportstoprofs_DDD_LInsertedItems" name="EnterOrderModel.reportstoprofs_DDD_LInsertedItems" value=""><input type="hidden" id="EnterOrderModel.reportstoprofs_DDD_LCustomCallback" name="EnterOrderModel.reportstoprofs_DDD_LCustomCallback" value="">
<table class="dxeListBox" cellspacing="0" cellpadding="0" id="EnterOrderModel.reportstoprofs_DDD_L" style="border-collapse:collapse;border-collapse:separate;">
<tbody>
<tr>
<td valign="top">
<div id="EnterOrderModel.reportstoprofs_DDD_L_D" class="dxlbd" style="width:100%;overflow-x:hidden;overflow-y:auto;">
<input id="EnterOrderModel.reportstoprofs_DDD_L_VI" type="hidden" name="EnterOrderModel.reportstoprofs$DDD$L" value="AAAA">
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;border-collapse:separate;visibility:hidden!important;display:none!important;">
<tbody>
<tr id="EnterOrderModel.reportstoprofs_DDD_L_LBI-1" class="dxeListBoxItemRow">
<td id="EnterOrderModel.reportstoprofs_DDD_L_LBI-1T0" class="dxeListBoxItem"> </td>
</tr>
</tbody>
</table>
<div id="EnterOrderModel.reportstoprofs_DDD_L_TS" style="display: none;">
</div>
<table id="EnterOrderModel.reportstoprofs_DDD_L_LBT" cellspacing="0" cellpadding="0" style="width:100%;border-collapse:collapse;border-collapse:separate;">
<tbody>
<tr class="dxeListBoxItemRow">
<td class="dxeListBoxItem" id="EnterOrderModel.reportstoprofs_DDD_L_LBI0T0">Select One</td>
</tr>
<tr class="dxeListBoxItemRow">
<td class="dxeListBoxItem" id="EnterOrderModel.reportstoprofs_DDD_L_LBI1T0">Macccc Dongle</td>
</tr>
<tr class="dxeListBoxItemRow">
<td class="dxeListBoxItem" id="EnterOrderModel.reportstoprofs_DDD_L_LBI2T0">Rock Start</td>
</tr>
<tr class="dxeListBoxItemRow">
<td class="dxeListBoxItem" id="EnterOrderModel.reportstoprofs_DDD_L_LBI3T0">Alliau babbaa</td>
</tr>
<tr class="dxeListBoxItemRow">
<td class="dxeListBoxItem" id="EnterOrderModel.reportstoprofs_DDD_L_LBI4T0">Mong star audomma</td>
</tr>
</tbody>
</table>
<div id="EnterOrderModel.reportstoprofs_DDD_L_BS" style="display: none;">
</div>
</div>
</td>
</tr>
</tbody>
</table>
<script id="dxss_1356993039" type="text/javascript">
<!--
aspxAddDisabledItems('EnterOrderModel.reportstoprofs_DDD_L',[[['dxeDisabled'],[''],['']]]);
var dxo = new ASPxClientListBox('EnterOrderModel.reportstoprofs_DDD_L');
window['EnterOrderModel.reportstoprofs_DDD_L'] = dxo;
dxo.uniqueID = 'EnterOrderModel.reportstoprofs$DDD$L';
dxo.SelectedIndexChanged.AddHandler(function (s, e) { aspxCBLBSelectedIndexChanged('EnterOrderModel.reportstoprofs', e); });
dxo.ItemClick.AddHandler(function (s, e) { aspxCBLBItemMouseUp('EnterOrderModel.reportstoprofs', e); });
dxo.RequireStyleDecoration();
dxo.styleDecoration.AddStyle('F','dxeFocused','');
dxo.savedSelectedIndex = 9;
dxo.itemsValue=['','SFIRTH','TANDE142','BBECK12','KBELLEGH','NBISSON','EBOLDUC','GBORSCHK','GBRISCOE','AAAA','PCAMERON','DCANTAGA','RCARROL2','SCAUVEL','GCAVE1','KCHRIST2','DCOLAPRE','HCUSHMAN','TDENNING','RDERHODG','ADUCHARM','REATON','TERB','MFARLEY4','EFERRELL','DFORTUNA','CFRADET','GGIOVINA','BGOLDBER','BGOODMA1','RGRAMADA','JGUBERNE','JHARTFO2','MHERNIAK','MHORNE3','MHUGGIN1','CHUNT21','JINTRAVA','PJANSEN1','RKANTAUT','DKELLETT','WKIRK1','LKOZMA','VKUSUMAK','RLAURILA','JLEACH1','KLEBLANC','FLEE2','BLESSARD','JMCCAMON','AMCCORM2','TNISSEN','JOLOMAN','EPAHAPI1','APETRIE1','ZRACZ','MRONAN','WROWE2','PROY','TSAVONI','JSNYDER5','LSTIERS','KSTRONG1','GTAIARIO','JTJONG','DTOTTEN','MTRENK1','CTURGEON','JVELLING','PWALWORT','WWELACKY','EWEST2','BWHITE7','SWHITEHE','BWILLI15','DWILLIA3','GWOOD5','KWOODBRI','MYETHON'];
dxo.isSyncEnabled = false;
dxo.isComboBoxList = true;
dxo.hasSampleItem = true;
dxo.isCallbackMode = true;
dxo.callbackPageSize = 100;
dxo.hoverClasses=['dxeListBoxItemHover'];
dxo.selectedClasses=['dxeListBoxItemSelected'];
dxo.disabledClasses=['dxeDisabled'];
dxo.InlineInitialize();
//-->
</script>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td style="background:url('/DXR.axd?r=1_25-7rgYm') no-repeat left top;"></td>
</tr>
<tr>
<td style="background:url('/DXR.axd?r=1_24-7rgYm') no-repeat left top;"></td>
<td style="background:url('/DXR.axd?r=1_26-7rgYm') no-repeat left top;">
<div style="height:5px;width:5px;">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script id="dxss_452203440" type="text/javascript">
<!--
var dxo = new ASPxClientPopupControl('EnterOrderModel.reportstoprofs_DDD');
window['EnterOrderModel.reportstoprofs_DDD'] = dxo;
dxo.uniqueID = 'EnterOrderModel.reportstoprofs$DDD';
dxo.Shown.AddHandler(function (s, e) { aspxDDBPCShown('EnterOrderModel.reportstoprofs', e); });
dxo.adjustInnerControlsSizeOnShow=false;
dxo.closeAction='CloseButton';
dxo.popupHorizontalAlign='LeftSides';
dxo.popupVerticalAlign='Below';
dxo.width=0;
dxo.height=0;
dxo.InlineInitialize();
//-->
</script>
<table id="EnterOrderModel.reportstoprofs_LP" class="dxeLoadingPanel" cellspacing="0" cellpadding="0" style="border-collapse:collapse;left:0px;top:0px;z-index:30000;display:none;">
<tbody>
<tr>
<td class="dx" style="padding-right:8px;"><img src="/DXR.axd?r=2_24-7rgYm" alt="" align="middle"></td>
<td class="dx" style="padding-left:0px;">Loading…</td>
</tr>
</tbody>
</table>
<div id="EnterOrderModel.reportstoprofs_LD" class="dxeLoadingDiv" style="left:0px;top:0px;z-index:29999;display:none;position:absolute;">
</div>
<script id="dxss_1042248493" type="text/javascript">
<!--
aspxAddHoverItems('EnterOrderModel.reportstoprofs',[[['dxeButtonEditButtonHover'],[''],['B-1'],,[['']],['Img']]]);
aspxAddPressedItems('EnterOrderModel.reportstoprofs',[[['dxeButtonEditButtonPressed'],[''],['B-1'],,[['']],['Img']]]);
aspxAddDisabledItems('EnterOrderModel.reportstoprofs',[[['dxeDisabled'],[''],['','I']],[['dxeDisabled dxeButtonDisabled'],[''],['B-1'],,[[{'spriteCssClass':'dxEditors_edtDropDownDisabled'}]],['Img']]]);
document.getElementById("EnterOrderModel.reportstoprofs_I").setAttribute("autocomplete", "off");
var dxo = new MVCxClientComboBox('EnterOrderModel.reportstoprofs');
window['EnterOrderModel.reportstoprofs'] = dxo;
dxo.callBack = function(arg) { ; };
dxo.RequireStyleDecoration();
dxo.styleDecoration.AddStyle('F','dxeFocused','');
dxo.incrementalFilteringMode='StartsWith';
dxo.isCallbackMode = true;
dxo.lastSuccessValue = 'AAAAA';
dxo.islastSuccessValueInit = true;
dxo.unobtrusiveValidationAttributes=eval(({'data-val-required':'Required','data-val':'true'}));
dxo.callbackUrl="/en-US/Orders/EnterOrder/ReportsToProf";
dxo.InlineInitialize();
//-->
</script>
<span class="commentText">*</span>
<span class="field-validation-valid" data-valmsg-for="EnterOrderModel.reportstoprofs" data-valmsg-replace="true"></span>
</td>
Selenium code to handle this complex dropdown selection
_driver is a variable of IWebDriver before use you have to initiate it e.g IWebDriver _driver = new ChromeDriver();
_driver.SelectDropDownByText(
clickId:"EnterOrderModel.reportstoprofs_B-1",
tableId:"EnterOrderModel.reportstoprofs_DDD_L_LBT",
visibleText:"Macccc Dongle");
Question is i have table in which i want to populate the values of file name and file size after user click the choose file button and select any number of files, Now the issue is if the user click choose files button second time i want to append the new values in the table and add the new file in the array so that it can uploaded.. my code is,
html form code:
<form id="simpleuploadform" method="post" action="upload" enctype="multipart/form-data">
<table class="span10" border="0">
<tr>
<td colspan="3">
<legend>Simple Upload</legend>
</td>
</tr>
<tr>
<td>
<input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
<div id="successdiv" hidden="true" class="label label-success">Image uploaded successfully</div>
<div id="errordiv" hidden="true" class="label label-error">Image not successfully uploaded</div>
<div id="streamdiv" hidden="true" class="label label-warning">Issue while uploading try again</div>
</td>
<td id="renameFile" align="right"></td>
<td id="removeFile" align="right"></td>
</tr>
<tr>
<td colspan="3">
<div id="uploaddiv">
<table id="uploadTable" class="table table-striped table-bordered" width="200" height="200" scrolling="yes">
<thead>
<tr>
<th>Title</th>
<th>Size</th>
</tr>
</thead>
<tbody id="tbodyid">
<tr id="tr0">
<td id="filetd0" height="10px" width="50px"></td>
<td id="filesizetd0" height="10px" width="5px"></td>
</tr>
<tr id="tr1">
<td id="filetd1" height="10px" width="50px"></td>
<td id="filesizetd1" height="10px" width="5px"></td>
</tr>
<tr id="tr2">
<td id="filetd2" height="10px" width="50px"></td>
<td id="filesizetd2" height="10px" width="5px"></td>
</tr>
<tr id="tr3">
<td id="filetd3" height="10px" width="50px"></td>
<td id="filesizetd3" height="10px" width="5px"></td>
</tr>
<tr id="tr4">
<td id="filetd4" height="10px" width="50px"></td>
<td id="filesizetd4" height="10px" width="5px"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td id="filecount" height="10px" width="50px"></td>
<td id="totalsize" height="10px" width="5px"></td>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="btn btn-primary" onClick="CloseAndRefresh();" value="Start Upload" id="startButton" disabled>
<input type="reset" class="btn btn-primary" onClick="Clear();" value="Clear" id="clearButton" disabled>
<input type="button" class="btn" onClick="window.close();" value="Close">
</td>
</tr>
</table>
javascript code:
<script type="text/javascript">
var totalsizeOfUploadFiles = 0;
function getFileSizeandName(input)
{
var select = $('#uploadTable tbody');
$('#renameFile').empty();$('#removeFile').empty();
if(input.files.length > 0)
{
$('#renameFile').append($('<a id="renameRec">Rename Selected</a>'));
$('#removeFile').append($('<a id="removeRec">Remove Selected</a>'));
$('#startButton').removeAttr("disabled", "disabled");
$('#clearButton').removeAttr("disabled", "disabled");
}
//if(input.files.length <= 5)
//{
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size;
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
var filename = input.files[i].name;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
if(i<=4)
{
$('#filetd'+i+'').text(filename);
$('#filesizetd'+i+'').text(filesizeInMB);
}
else if(i>4)
select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles += parseFloat(filesizeInMB);
$('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
if(i==0)
$('#filecount').text("1file");
else
{
var no = parseInt(i) + 1;
$('#filecount').text(no+"files");
}
}
//}
}
function CloseAndRefresh()
{
var daa = '<%=status%>';
if(daa == "true")
$('#successdiv').show();
else if(daa == "false")
$('#errordiv').show();
else
$('#streamdiv').show();
opener.location.reload(true);
self.close();
}
function Clear()
{
$('#uploadTable tbody tr td').each(function(){
$(this).text("");
});
$('#uploadTable tfoot tr td').each(function(){
$(this).text("");
});
}
i am trying to do as like this http://www.shutterfly.com/ image upload.
any help will be appreciated, thank you friends...
You are navigating away using javascript, function CloseAndRefresh on clicking submit button.
What actually happens is that the uploading request is being submitted while the CloseAndRefresh function is being executed at almost the same time using different thread. If the upload request is not fast enough, the web page will get refresh first and your upload request get terminated immediately. There is no easy way to prevent this using your existing code.
You should use advanced method of uploading like jQuery uploading plugin to send the request. The plugin provide an binder to execute function on successful/failed submittsion.
Thank you gigadot, i solve the issue as like below,
The html form have the same code as i posted earlier, in the previous js code i have the CloseAndRefresh() method i remove it now from js as well as from the submit button onclick event.
When the form action called the controller, in which i have the code
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String UploadReceipts(#RequestParam("files[]") List<MultipartFile> file, Model model) throws IOException {
boolean status = false;
try
{
for(int i=0; i< file.size(); i++)
{
if(!file.get(i).isEmpty())
{
CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
status = simpleUploadService.uploadFileandSave(cm);
model.addAttribute("status", status);
}
}
}
catch (IOException e) {
status = false;
model.addAttribute("status", status);
}
return "pages/simpleUploadStatus";
}
Now i redirect it to another page in which i throws the appropriate messages for the user.
that's all...