前台代码
<tr>
<td>图片地址:</td>
<td>
<asp:FileUpload ID="FileUpLoad1" CssClass="txtHInput" runat="server" />
</td>
<td><asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td>
</tr>
<tr>
<td>图片地址:</td>
<td>
<asp:FileUpload ID="FileUpLoad2" CssClass="txtHInput" runat="server" />
</td>
<td> </td>
</tr>
<tr>
<td>图片地址:</td>
<td>
<asp:FileUpload ID="FileUpLoad3" CssClass="txtHInput" runat="server" />
</td>
<td> </td>
</tr>
<tr>
<td>图片备注:</td>
<td>
<asp:TextBox ID="txtRemark" runat="server" CssClass="txtHInput" MaxLength="100"
TextMode="Password" Height="139px" Rows="10" Width="285px"></asp:TextBox> </td>
<td>为该图片填写补充信息</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="ImageSave" runat="server" Text="上传图片"
οnclick="ImageSave_Click" />
<asp:LinkButton ID="LinkButton1" runat="server" Font-Bold="False"
PostBackUrl="~/AddImg.aspx">继续添加</asp:LinkButton>
</td>
<td></td>
</tr>
后台代码
protected void ImageSave_Click(object sender, EventArgs e)
{
try
{
if (FileUpLoad1.PostedFile.FileName == "" && FileUpLoad2.PostedFile.FileName == "" && FileUpLoad3.PostedFile.FileName == "")
{
this.lb_info.Text = "请选择文件!";
}
else
{
HttpFileCollection myFiles = Request.Files;
for (int i = 0; i < myFiles.Count; i++)
{
string filepath = FileUpLoad1.PostedFile.FileName;
HttpPostedFile myPostFile = myFiles[i];
if (myPostFile.ContentLength > 0)
{
if (IsAllowedExtension(myPostFile) == true)
{
string filename = GetImageName();
string serverpath = Server.MapPath("UpFileImg/") + filename;
myPostFile.SaveAs(serverpath);
DataUserImg UserImage=new DataUserImg();
UserImage.userid=6;
UserImage.imgname="UpFileImg/"+filename;
UserImage.remark=txtRemark.Text;
if( BLLUserImage.AddImage(UserImage))
{
Common.MessageBox.myScriptMes(Page, "if(confirm(\"图片保存成功,是否继续添加?否则返回人员列表。\")) {location.href=\"AddImg.aspx\"} else {location.href=\"UserInfoManager.aspx\"} ", "Suess");
}
}
else
{
Common.MessageBox.Show(Page, "只能上传.gif、jpg、.bmp、.png格式的文件", "AddImg.aspx", "error");
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private string GetImageName()
{
string NowStr = DateTime.Now.ToString().Replace('-', 'B').Replace(':', 'F').Replace(' ', 'K').ToString();
Random rand = new Random();
string Randstr = rand.NextDouble().ToString().Replace('.', 'A').Substring(0, 8);
string FileName = NowStr + Randstr;
return FileName;
}
private static bool IsAllowedExtension(HttpPostedFile upfile)
{
string strOldFilePath = "";
string strExtension = "";
string[] arrExtension = { ".gif", ".jpg", ".bmp", ".png" };
if (upfile.FileName != string.Empty)
{
strOldFilePath =upfile.FileName;//获得文件的完整路径名
strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//获得文件的扩展名,如:.jpg
for (int i = 0; i < arrExtension.Length; i++)
{
if (strExtension.Equals(arrExtension[i]))
{
return true;
}
}
}
return false;
}