【发布时间】:2011-06-30 21:21:38
【问题描述】:
我在 ASP.NEt WebForms 中使用 UpdatePanel 来上传图像。我想将文件名保存在数据库中,但不是路径。我正在使用以下代码
<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>
在 UploadbuttonClick 方法中,我将路径设置为图像宽度Image1.ImageUrl = virtualFilePath;,其中virtualFilePath 是文件的完整虚拟路径。保存数据时,数据库包含文件的完整路径,但我只需要文件名。
编辑 1: 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;
}
}
编辑 2: 保存到数据库的代码
<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>
【问题讨论】:
-
UploadbuttonClick 使用 FileUpload1.FileName 来获取文件名。我更新我的问题以显示代码
-
但这是你的问题,你说“我想将文件名保存在数据库中,而不是路径。”您已经知道如何获取文件名 (FileUpload1.FileName)。您将路径保存在数据库中的什么位置?
-
virtualFilePath 是 /images/news/imagename.jpg,但我只想在数据库中存储 imagename.jpg。
-
@magol:你是在混淆数据库和文件系统吗? FileUpload.SaveAs 将文件保存在网络服务器上,而不是在 dbms 中。
-
@Tim Schmelter 我也是这么想的,我没有看到这个问题的主题“保存前在 UpdatePanel 中格式化数据”与“我想将文件名保存在数据库中”之间的关系,但不是路径。”。还是不明白你的问题@magol 抱歉 :(
标签: c# asp.net data-binding webforms