In my webform, I have a fileupload control and a button. When the button is clicked after selecting a file to upload, the image should be saved and renamed with a unique GUID.
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
string extension = string.Empty;
try
{
// Check if Fileupload control has a file
if (FileUpload1.HasFile)
{
// Get selected image extension
extension = Path.GetExtension(FileUpload1.FileName).ToLower();
// Check if image is of a valid type
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
{
// Create a unique name for the file
fileName = Guid.NewGuid().ToString() + extension;
// Create a path for the image to store
HiddenField1.Value = fileName;
filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
// Save the image in a folder
FileUpload1.SaveAs(filePath);
// Show the panel and load the uploaded image in the image control.
// pnlCrop.Visible = true;
}
The code above successfully saves the image and sends the GUID to the hiddenfield. Now, I want to retrieve the value of the hiddenfield in a client-side variable and display it as an alert.
<script type="text/javascript">
function showfilename() {
setTimeout(function () {
var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
alert(dpGUID);
},3000)
}
</script>
Why use a timeout? I need to ensure that I read the value of the hiddenfield only after it has been assigned a value on button click.
It is possible to use two functions on a button click, one on the client side and one on the server side, as shown here:
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />
Is this setup causing any issues?