asp.net文件上传解决方案(图片上传、单文件上传、多文件上传、检查文件类型)

 更新时间:2021年9月22日 10:10  点击:1502

小编之前也介绍了许多ASP.NET文件上传的解决案例,今天来个asp.net文件上传大集合。

1 使用标准HTML来进行图片上传
前台代码:

<body> 
 <form id="form1" runat="server"> 
 <div> 
  <table> 
   <tr> 
    <td colspan="2" style="height: 21px" > 
     使用标准HTML来进行图片上传</td> 
   </tr> 
   <tr> 
    <td style="width: 400px"> 
     <input id="InputFile" style="width: 399px" type="file" runat="server" /></td> 
    <td style="width: 80px"> 
     <asp:Button ID="UploadButton" runat="server" Text="上传图片" OnClick="UploadButton_Click" /></td> 
   </tr> 
   <tr> 
    <td colspan="2" > 
     <asp:Label ID="Lb_Info" runat="server" ForeColor="Red"></asp:Label></td>     
   </tr> 
  </table>  
 </div> 
 </form> 
</body>


后台代码:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{ 
 protected void Page_Load(object sender, EventArgs e) 
 { 

 } 
 protected void UploadButton_Click(object sender, EventArgs e) 
 { 
  string uploadName = InputFile.Value;//获取待上传图片的完整路径,包括文件名 
  //string uploadName = InputFile.PostedFile.FileName; 
  string pictureName = "";//上传后的图片名,以当前时间为文件名,确保文件名没有重复 
  if (InputFile.Value != "") 
  { 
   int idx = uploadName.LastIndexOf("."); 
   string suffix = uploadName.Substring(idx);//获得上传的图片的后缀名 
   pictureName = DateTime.Now.Ticks.ToString() + suffix; 
  } 
  try 
  { 
   if (uploadName != "") 
   { 
    string path = Server.MapPath("~/images/"); 
    InputFile.PostedFile.SaveAs(path + pictureName); 
   } 
  } 
  catch (Exception ex) 
  { 
   Response.Write(ex); 
  } 
 } 
}

2 单文件上传
这是最基本的文件上传,在asp.net1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件, 很不好用。其实所有文件上传的美丽效果都是从这个FileUpload控件衍生,第一个例子虽然简单却是根本。
前台代码:

<body> 
 <form id="form1" runat="server"> 
 <div> 
  <table style="width: 90%"> 
   <tr> 
    <td style="width: 159px" colspan=2> 
     <strong><span style="font-size: 10pt">最简单的单文件上传</span></strong></td> 
   </tr> 
   <tr> 
    <td style="width: 600px"> 
     <asp:FileUpload ID="FileUpload1" runat="server" Width="600px" /></td> 
    <td align=left> 
     <asp:Button ID="FileUpload_Button" runat="server" Text="上传图片" OnClick="FileUpload_Button_Click" /></td> 
   </tr> 
   <tr> 
    <td colspan=2> 
     <asp:Label ID="Upload_info" runat="server" ForeColor="Red" Width="767px"></asp:Label></td> 
   </tr> 
  </table>  
 </div> 
 </form> 
</body>

后台代码:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{ 
 protected void Page_Load(object sender, EventArgs e) 
 { 

 } 
 protected void FileUpload_Button_Click(object sender, EventArgs e) 
 { 
  try 
  { 
   if (FileUpload1.PostedFile.FileName == "") 
   //if (FileUpload1.FileName == "") 
   //if (!FileUpload1.HasFile)  //获取一个值,该值指示 System.Web.UI.WebControls.FileUpload 控件是否包含文件。包含文件,则为 true;否则为 false。 
   { 
    this.Upload_info.Text = "请选择上传文件!"; 
   } 
   else 
   { 
    string filepath = FileUpload1.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg 
    //string filepath = FileUpload1.FileName;    //得到上传的文件名20022775_m.jpg 
    string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg 
    string serverpath = Server.MapPath("~/images/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg 
    FileUpload1.PostedFile.SaveAs(serverpath);//将上传的文件另存为 
    this.Upload_info.Text = "上传成功!"; 
   } 
  } 
  catch (Exception ex) 
  { 
   this.Upload_info.Text = "上传发生错误!原因是:" + ex.ToString(); 
  } 
 } 
}


3、多文件上传
前台代码:

<body> 
 <form id="form1" runat="server"> 
 <div> 
 <table style="width: 343px"> 
   <tr> 
    <td style="width: 100px"> 
     多文件上传</td> 
    <td style="width: 100px"> 
    </td> 
   </tr> 
   <tr> 
    <td style="width: 100px"> 
     <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /> 
     </td> 
    <td style="width: 100px"> 
     </td> 
   </tr> 
   <tr> 
    <td style="width: 100px"> 
     <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td> 
    <td style="width: 100px"> 
    </td> 
   </tr> 
   <tr> 
    <td style="width: 100px"> 
     <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td> 
    <td style="width: 100px"> 
    </td> 
   </tr> 
   <tr> 
    <td style="width: 100px"> 
     <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上传" /> 
     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td> 
    <td style="width: 100px"> 
    </td> 
   </tr> 
  </table> 
 </div> 
 </form> 
</body>


后台代码:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{ 
 protected void Page_Load(object sender, EventArgs e) 
 { 

 } 
 protected void bt_upload_Click(object sender, EventArgs e) 
 { 
  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++) 
   { 
    HttpPostedFile mypost = myfiles[i]; 
    try 
    { 
     if (mypost.ContentLength > 0) 
     { 
      string filepath = mypost.FileName;//C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg 
      string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg 
      string serverpath = Server.MapPath("~/images/") + filename;//C:\Inetpub\wwwroot\WebSite2\images\20022775_m.jpg 
      mypost.SaveAs(serverpath); 
      this.lb_info.Text = "上传成功!"; 
     } 
    } 
    catch (Exception ex) 
    { 
     this.lb_info.Text = "上传发生错误!原因:" + ex.Message.ToString(); 
    } 
   } 
  } 
 } 
}

4、客户端检查上传文件类型(以上传图片为例)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
 <title>客户端检查上传文件类型</title> 
 <script language="javascript"> 
 function Check_FileType() 
 { 
  var str=document.getElementById("FileUpload1").value; 
  var pos=str.lastIndexOf("."); 
  var lastname=str.substring(pos,str.length); 
  if(lastname.toLowerCase()!=".jpg"&&lastname.toLowerCase()!=".gif") 
  { 
   alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型"); 
   return false; 
  } 
  else 
  { 
   return true; 
  }   
 } 
 </script> 
</head> 
<body> 
 <form id="form1" runat="server"> 
 <div> 
  <table> 
   <tr> 
    <td colspan="2"> 
     客户端检查上传文件类型</td>     
   </tr> 
   <tr> 
    <td style="width: 444px"> 
     <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td> 
    <td style="width: 80px"> 
     <asp:Button ID="bt_upload" runat="server" Text="上传图片" OnClick="bt_upload_Click" OnClientClick="return Check_FileType()" /></td> 
   </tr> 
   <tr> 
    <td colspan="2" style="height: 21px"> 
     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td>     
   </tr> 
  </table>  
 </div> 
 </form> 
</body> 
</html>

注意:点击上传时先触发客户端事件OnClientClick="return Check_FileType()"

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{ 
 protected void Page_Load(object sender, EventArgs e) 
 { 

 } 

 protected void bt_upload_Click(object sender, EventArgs e) 
 { 
  try 
  { 
   if (FileUpload1.PostedFile.FileName == "") 
   { 
    this.lb_info.Text = "请选择文件!"; 
   } 
   else 
   { 
    string filepath = FileUpload1.PostedFile.FileName; 
    //if (!IsAllowedExtension(FileUpload1)) 
    //{ 
    // this.lb_info.Text = "上传文件格式不正确!"; 
    //} 
    if (IsAllowedExtension(FileUpload1) == true) 
    { 
     string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 
     string serverpath = Server.MapPath("~/images/") + filename; 
     FileUpload1.PostedFile.SaveAs(serverpath); 
     this.lb_info.Text = "上传成功!"; 
    } 
    else 
    { 
     this.lb_info.Text = "请上传图片!"; 
    } 
   } 
  } 
  catch (Exception ex) 
  { 
   this.lb_info.Text = "上传发生错误!原因:" + ex.ToString(); 
  } 
 } 
 private static bool IsAllowedExtension(FileUpload upfile) 
 { 
  string strOldFilePath = ""; 
  string strExtension=""; 
  string[] arrExtension ={ ".gif", ".jpg", ".bmp", ".png" }; 
  if (upfile.PostedFile.FileName != string.Empty) 
  { 
   strOldFilePath = upfile.PostedFile.FileName;//获得文件的完整路径名 
   strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//获得文件的扩展名,如:.jpg 
   for (int i = 0; i < arrExtension.Length; i++) 
   { 
    if (strExtension.Equals(arrExtension[i])) 
    { 
     return true; 
    } 
   } 
  } 
  return false; 
 } 
}

注意:若去掉客户端的脚本和客户端事件OnClientClick="return Check_FileType()",在后台代码
改为:

if (!IsAllowedExtension(FileUpload1)) 
    { 
     this.lb_info.Text = "上传文件格式不正确!"; 
    } 


else if (IsAllowedExtension(FileUpload1) == true)
即变成服务器端检查上传文件类型。
5、服务器端检查上传文件的类型(文件内部真正的格式)

<body> 
 <form id="form1" runat="server"> 
 <div> 
  <table> 
   <tr> 
    <td colspan="2"> 
     服务器检查上传文件类型</td>     
   </tr> 
   <tr> 
    <td style="width: 444px"> 
     <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td> 
    <td style="width: 80px"> 
     <asp:Button ID="bt_upload" runat="server" Text="上传图片" OnClick="bt_upload_Click" /></td> 
   </tr> 
   <tr> 
    <td colspan="2" style="height: 21px"> 
     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td>     
   </tr> 
  </table>  
 </div> 
 </form> 
</body>

后台代码:

using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.IO; 

public partial class _Default : System.Web.UI.Page 
{ 
 protected void Page_Load(object sender, EventArgs e) 
 { 

 } 
 protected void bt_upload_Click(object sender, EventArgs e) 
 { 
  try 
  { 
   if (FileUpload1.PostedFile.FileName == "") 
   { 
    this.lb_info.Text = "请选择文件!"; 
   } 
   else 
   { 
    string filepath = FileUpload1.PostedFile.FileName; 
    if (IsAllowedExtension(FileUpload1) == true) 
    { 
     string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 
     string serverpath = Server.MapPath("images/") + filename; 
     FileUpload1.PostedFile.SaveAs(serverpath); 
     this.lb_info.Text = "上传成功!"; 
    } 
    else 
    { 
     this.lb_info.Text = "请上传图片"; 
    } 
   } 
  } 
  catch (Exception error) 
  { 
   this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 
  } 
 } 
 private static bool IsAllowedExtension(FileUpload upfile) 
 { 
  FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read); 
  BinaryReader r = new BinaryReader(fs); 
  string fileclass = ""; 
  byte buffer; 
  try 
  { 
   buffer = r.ReadByte(); 
   fileclass = buffer.ToString(); 
   buffer = r.ReadByte(); 
   fileclass += buffer.ToString(); 
  } 
  catch 
  { 
    
  } 
  r.Close(); 
  fs.Close(); 
  if (fileclass == "255216" || fileclass == "7173"||fileclass=="6677"||fileclass=="13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
  { 
   return true; 
  } 
  else 
  { 
   return false; 
  } 
 } 
}

为大家推荐一个专题,供大家学习:《ASP.NET文件上传汇总》

是不是内容很精彩,喜欢的朋友就收藏起来吧,以后在遇到ASP.NET文件上传问题的时候能够有所帮助。

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
  • php文件上传你必须知道的几点

    本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • PHP swfupload图片上传的实例代码

    PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • 百度编辑器ueditor修改图片上传默认路径

    本案例非通用,仅作笔记以备用 修改后的结果是 百度编辑器里上传的图片路径为/d/file/upload1...2014-07-03
  • 借助FileReader实现将文件编码为Base64后通过AJAX上传

    这篇文章主要介绍了借助FileReader实现将文件编码为Base64后通过AJAX上传的方法,包括后端对文件数据解码并保存的PHP代码,需要的朋友可以参考下...2015-12-25
  • jQuery+ajax简单实现文件上传的方法

    这篇文章主要介绍了jQuery+ajax简单实现文件上传的方法,结合实例形式简单分析了jQuery基于ajax的post方法进行文件传输及asp.net后台处理技巧,需要的朋友可以参考下...2016-06-12
  • js实现上传文件添加和删除文件选择框

    这篇文章主要为大家详细介绍了js实现上传文件添加和删除文件选择框 ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-10-25
  • 适用于初学者的简易PHP文件上传类

    本文实例讲述了PHP多文件上传类,分享给大家供大家参考。具体如下:<&#63;phpclass Test_Upload{ protected $_uploaded = array(); protected $_destination; protected $_max = 1024000; protected $_messages =...2015-10-30
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • Java实现将图片上传到webapp路径下 路径获取方式

    这篇文章主要介绍了Java实现将图片上传到webapp路径下 路径获取方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-11-12
  • js 实现文件上传样式详情

    这篇文章主要介绍了js 实现文件上传样式,下面文章举例说明js 是如何实现文件上传样式的,附有代码详细解说,需要的朋友可以参考一下,希望对你有所帮助...2021-10-21
  • asp.net通过消息队列处理高并发请求(以抢小米手机为例)

    这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • PHP利用APC模块实现大文件上传进度条的方法

    php 大文件带进度的上传,一直是一个令php程序员很苦恼的问题。查询baidu 、Google ,大体做带进度的上传方式为:flash+php,socket,apc+php等,下面我介绍了apc +php+ajax制作的带进度的上传,并贴出源码,希望对大家有用。 Altern...2015-10-30
  • ASP.NET单选按钮控件RadioButton常用属性和方法介绍

    RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22