背景:VisualStuio2005;
实现图片上传及显示图片功能;
服务器端文件上传目录:upload
实现:
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string fullFileName = this.FileUpload1.PostedFile.FileName;
string FileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1);
if (FileType == "jpg" || FileType == "gif" || FileType == "bmp" || FileType == "jpeg")
{
this.Image1.ImageUrl = fullFileName;
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("upload" + "\\" + FileName));
this.Image1.ImageUrl = "upload/" + FileName;
Response.Write("图片上传成功!"+"<br>");
Response.Write("源文件为:" + fullFileName);
}
else
{
//Response.Write("图片格式不符,请重新上传!");
Response.Write("<script language='javascript'>alert('图片格式不符,请重新上传!');</script>");
}
}
catch (Exception ex)
{
Response.Write("上传失败!");
}
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string fullFileName = this.FileUpload1.PostedFile.FileName;
string FileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1);
if (FileType == "jpg" || FileType == "gif" || FileType == "bmp" || FileType == "jpeg")
{
this.Image1.ImageUrl = fullFileName;
this.FileUpload1.PostedFile.SaveAs(Server.MapPath("upload" + "\\" + FileName));
this.Image1.ImageUrl = "upload/" + FileName;
Response.Write("图片上传成功!"+"<br>");
Response.Write("源文件为:" + fullFileName);
}
else
{
//Response.Write("图片格式不符,请重新上传!");
Response.Write("<script language='javascript'>alert('图片格式不符,请重新上传!');</script>");
}
}
catch (Exception ex)
{
Response.Write("上传失败!");
}
}
}
注意:上传文件目录upload必须设置可写权限,否则会插入失败
转载于:https://blog.51cto.com/hndtraveller/171152