I’m using an UpdatePanel in ASP.NEt WebForms to upload a image. I want to save the filename in the database, but NOT the path. I’m using following code
<asp:TemplateField FooterText="Image 1" HeaderText="Image 1">
<ItemTemplate>
<asp:Image ID="Image11" runat="server" ImageUrl='<%# Bind("pic") %>' Height="50px" onerror="this.style.display='none'" />
</ItemTemplate>
<EditItemTemplate>
<asp:UpdatePanel ID="updatPanelImg1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="uploadbutton" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button runat="server" Text="Add image" OnClick="UploadbuttonClick" />
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("pic") %>' onerror="this.style.display='none'" />
</ContentTemplate>
</asp:UpdatePanel>
</EditItemTemplate>
</asp:TemplateField>
And in the UploadbuttonClick method, I set the path to the image width Image1.ImageUrl = virtualFilePath; where virtualFilePath is the full virtual path to the file. When the data is saved, the database contains the full path to the file, but I only whant the file name.
Edit 1:
The code for UploadbuttonClick:
protected void UploadbuttonClick(object sender, EventArgs e)
{
var button = (Button)sender;
var fileUpload = (FileUpload)button.Parent.FindControl("FileUpload1");
var imageViewer = (Image)button.Parent.FindControl("Image1");
if (fileUpload.HasFile)
{
string fileName = fileUpload.FileName;
fileName = RemoveInvalidChars(fileName);
const string virtualPath = @"/images/news/";
string serverPath = Server.MapPath(virtualPath);
string serverFilePath = Path.Combine(serverPath, fileName);
string virtualFilePath = Path.Combine(virtualPath, fileName);
fileUpload.SaveAs(serverFilePath);
imageViewer.ImageUrl = virtualFilePath;
}
}
Edit 2:
Code to save to the database
<asp:SqlDataSource
ID="SqlDataSourceNews"
runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
UpdateCommand="UPDATE [foo] SET [pic] = @pic WHERE [id] = @id">
<UpdateParameters>
<asp:Parameter Name="pic" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="pic" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
You are binding the
ImageUrlattribute in your ItemTemplate (in a GridView or FormView probably?).So when you update, this value will be bound to the
<asp:Parameter Name="pic" />in theSqlDataSourcecontrol. But in the code behind file you set this value to the complete virtual path (because you want the image to be displayed correctly).So that is why this complete virtual path is saved to the database. To fix it you must bind the parameter value to a hidden control, and only use eval for the image control:
In your code behind, set the value for the hidden control to the filename: