I want to implement a clickable image which will prompt image upload, user upload image, then display the image. So I used an ImageButton
which will call a invisible FileUpload
(currently visible) for image upload. However, onchange()
doesn’t seem to work, when I check, it seems to be the image is not uploaded to the FileUpload
control.
So I tried debugging by making the FileUpload
visible and click on the control directly click on the FileUpload
control and select a photo, the image name is shown in the control. But when I use Javascript to click on FileUpload
when ImageButton
is clicked, and upload an image, the image name is not shown in the control, it remains ‘No file chosen’, meaning the image is not uploaded. Why is that?
Javascript code written on top of the page:
function chooseFile() {
$("#FileUpload1").click();
}
function fileChanged() {
//do something
}
ASP.NET code:
<asp:FileUpload ID="FileUpload1" runat="server" onchange="fileChanged()"/>
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="chooseFile()" ImageUrl="images/placeholder.png" />
EDIT 1
Tried using ClientIdMode='static'
ASPX Code:
function chooseFile() {
$("#<%=FileUpload1.ClientID%>").click());
}
Generated Code:
function chooseFile() {
$("#FileUpload1").click());
}
Control code:
<input type="file" name="FileUpload1" id="FileUpload1" onchange="fileChanged()" />
<input type="image" name="ImageButton1" id="ImageButton1" src="images/placeholder.png" onclick="chooseFile();" />
2
Answers
Okay, I realize that the file is empty because there is a postback happened right after the
ImageButton
is clicked, so even though it triggers the Javascript to click on theFileUpload
and pops up file explorer for file selection, the connection between the file explorer andFileUpload
is broken because of the postback.To avoid postback when
ImageButton
is clicked, I programmatically setOnClick
attribute of theImageButton
in Page_Load() like this, it calls thechooseFile()
Javascript function, and return a false which stops the program from having a postback. Once it theFileUpload
detects a file has been uploaded by usingonchange
, it callsfileChanged()
which replaces the image insideImageButton
.aspx Code:
using ClientIDMode static as below to keep same id when render server side control
or acccess control in javascript using below