上传代码:
前端
<input type="file" id="Txb_PicUrl" runat="server" title="浏览" size="34" />
<div class="DetailTable_NoticePoint" style="display:inline; ">要求:二寸免冠近照;jpg、png、gif格式;大小1M以下</div>
后台
Jz_ProductController objJz_Products = new Jz_ProductController();
Jz_ProductInfo objJz_Product = new Jz_ProductInfo();
// 文件客户端路径
HtmlInputFile HiFile = (HtmlInputFile)this.FindControl("Txb_PicUrl");
// 上传的图片文件名
string strImageFilename="";
if (HiFile == null || HiFile.PostedFile.FileName.Length == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请上传照片文件...')", true);
return;
}
else
{
strImageFilename = HiFile.PostedFile.FileName;
//获取文件扩展名
string strFileName_Kz = HiFile.PostedFile.ContentType.ToString();
strFileName_Kz = strFileName_Kz.Substring(strFileName_Kz.Length - 4);
if (strFileName_Kz == "jpeg" || strFileName_Kz == "/png" || strFileName_Kz == "/gif")
{
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('照片只允许上传JPG、PNG、GIF格式的文件...')", true);
return;
}
//判断文件大小,不允许超过1M
if (HiFile.PostedFile.ContentLength > 1048576)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('照片文件大小不超过1M...')", true);
return;
}
else
{
//新文件名=日期+原文件名
strImageFilename = DateTime.Now.ToFileTime().ToString("") +strImageFilename ;
}
}
// 图像文件
objJz_Product.PicUrl = strImageFilename;
// 站点物理路径
string strHostFilePath = Request.PhysicalApplicationPath;
//strHostFilePath = strHostFilePath.Substring(0, strHostFilePath.LastIndexOf("\\"));
//strHostFilePath = strHostFilePath.Substring(0, strHostFilePath.LastIndexOf("\\"));
// 拼合保存到服务的文件名
strHostFilePath = strHostFilePath + "DesktopModules\\YourCompany.Jz_Product\\ProductPic\\";
//Response.Write(strHostFilePath.ToString());
//Response.End();
HiFile.PostedFile.SaveAs(strHostFilePath + strImageFilename);
//相应的值赋给数据库字段
objJz_Product.Category = ddlCategory.SelectedItem.Value;
objJz_Product.ProductName = Txb_ProductName.Text;
objJz_Product.ProductContent = Txb_ProductContent.Text;
objJz_Product.Location = Txb_Location.Text;
objJz_Product.Price = decimal.Parse(Txb_Price.Text.ToString());
objJz_Product.ProductCreatedDate = DateTime.Now;
objJz_Product.Attachment = Txb_Attachment.Text;
//保存数据操作
objJz_Products.Add_Product(objJz_Product);
展现代码:
前端
<td align="center" valign="middle" >
<asp:Image ID="img_Kszp" Width="300px" Height="200px" runat="server"/>
</td>
后台
// 获取并显示产品图片
string strKszp = objJz_GetProduct.PicUrl.Trim();
// 绑定显示考生照片
if (strKszp != "")
{
ViewState["Kszp"] = strKszp;
string strImageUrl = "";
strImageUrl = Request.Url.AbsoluteUri;
strImageUrl = strImageUrl.Substring(0, strImageUrl.IndexOf("/", 7));
strImageUrl = strImageUrl + "/DesktopModules/YourCompany.Jz_Product/ProductPic/" + strKszp;
img_Kszp.ImageUrl = strImageUrl;
}