Article: Upload Image file and display in Image control in ASP.Net using C# and VB.Net
I am trying to upload the file same like this and trying to store path in one variable but as soon as image gets upload the variables get empty.
string imageId = "", fileExtension = "", filePath = "";
protected void btnAttachImage_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile)
{
// Generate a unique ID for the image
imageId = GenerateImageId();
// Get the file extension
fileExtension = Path.GetExtension(fileUpload.FileName);
// Save the file with the ID and extension
filePath = Server.MapPath("~/Images/" + imageId + fileExtension);
fileUpload.SaveAs(filePath);
// Set the image URL to display the uploaded image
Image1.ImageUrl = "~/Images/" + imageId + fileExtension;
//lblFileName.Text = fileUpload.FileName;
}
else
{
// Handle case when no file is selected
}
}
private string GenerateImageId()
{
string code = txtCmpId.Text;
return code;
}
<asp:Image ID="Image1" runat="server" Width="150" Height="150" CssClass="custom-image" />
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="btnAttachImage" runat="server" Text="Attach Image" OnClick="btnAttachImage_Click" Style="display: none" />