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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值