JS上传图片

<tr valign="top">
<td bgcolor="#fbfcff" style="width:10%;">图片</td>
<td bgcolor="#fbfcff" >
<div style="float:left; width:30px">
<input type="button" value="+" onclick="addFile()" />
</div>
<div id="divFile" style="float:left">
<div>
<input id="File1" type="file" style="width:400px" runat="server" name="files">&nbsp;
</div>
</div>
</td>
</tr>

protected void btnOK_Click(object sender, EventArgs e)
{
HttpFileCollection myFile = HttpContext.Current.Request.Files;
int iFileCount = myFile.Count;
//验证文件格式
for (int i = 0; i < iFileCount; i++)
{
HttpPostedFile hpFile = myFile[i];
if (hpFile.ContentLength != 0)
{
string fileName = System.IO.Path.GetFileName(hpFile.FileName);
string nowtime = DateTime.Now.ToString("yyyyMMddhhmmssff") + i;//为了使文件名称不重复
//获得文件名扩展
string fileExtension = System.IO.Path.GetExtension(fileName);
if (IsAllowedExtension(fileExtension) == false)
{
Web.MessageBox.Show(this, "文件格式不正确,请上传jpg或gif格式的!");
return;
}
//验证文件大小
if (hpFile.ContentLength > 2*1024)
{
Web.MessageBox.Show(this, "文件超过大小限制,请先处理图片!");
return;
}
}
}

for (int i = 0; i < iFileCount; i++)
{
HttpPostedFile hpFile = myFile[i];
if (hpFile.ContentLength != 0)
{
string fileName = System.IO.Path.GetFileName(hpFile.FileName);
string nowtime = DateTime.Now.ToString("yyyyMMddhhmmssff") + i;//为了使文件名称不重复
//获得文件名扩展
string fileExtension = System.IO.Path.GetExtension(fileName);

hpFile.SaveAs(Server.MapPath("~/UpLoad/File/") + nowtime + fileExtension);
Model.Img Img = new Model.Img();
Img.Img_url = "/UpLoad/File/" + nowtime + fileExtension;
Img.ID = infoid;
//数据库更新代码!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
new BLL.Img().Add(Img);
Web.MessageBox.Show(this,"上传成功!");
}
}
}

//验证扩展名
public static bool IsAllowedExtension(string FileType)
{
string[] allowedextensions = { ".jpg", ".JPG", ".gif", ".GIF" };
//允许上传的扩展名,可以改成从配置文件中读出
if (FileType != string.Empty)
{
//判断该扩展名是否合法
for (int i = 0; i < allowedextensions.Length; i++)
{
if (FileType.Equals(allowedextensions[i]))
{
return true;
}
}
}
return false;
}

你可能感兴趣的:(String,object,File,扩展,float,button)