ASP.NET多文件上传方法

    技术2022-05-11  145

    前台代码

    <script language="Javascript">function addFile() { var str = '<INPUT type="file" size="30" NAME="File"><br>' document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)

    } </script>

    <form id="form1" method="post" runat="server" enctype="multipart/form-data"><div align="center"><h3>多文件上传</h3><P id="MyFile"><INPUT type="file" size="30" NAME="File"><br></P><P><input type="button" value="增加(Add)" οnclick="addFile()"> <input οnclick="this.form.reset()" type="button" value="重置(ReSet)"><asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button></P><P><asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" Width="500px"BorderStyle="None" BorderColor="White"></asp:Label></P></div></form>

    后台代码

    protected System.Web.UI.WebControls.Button UploadButton;protected System.Web.UI.WebControls.Label strStatus;

    private void Page_Load(object sender, System.EventArgs e){/// 在此处放置用户代码以初始化页面if (this.IsPostBack) this.SaveImages();}

    private Boolean SaveImages(){///'遍历File表单元素HttpFileCollection files = HttpContext.Current.Request.Files;

    /// '状态信息System.Text.StringBuilder strMsg = new System.Text.StringBuilder();strMsg.Append("上传的文件分别是:<hr color=red>");try{ for(int iFile = 0; iFile < files.Count; iFile++) {  ///'检查文件扩展名字  HttpPostedFile postedFile = files[iFile];  string fileName,fileExtension,file_id;

      //取出精确到毫秒的时间做文件的名称  int year = System.DateTime.Now.Year;  int month = System.DateTime.Now.Month;  int day = System.DateTime.Now.Day;  int hour = System.DateTime.Now.Hour;  int minute = System.DateTime.Now.Minute;  int second = System.DateTime.Now.Second;  int millisecond = System.DateTime.Now.Millisecond;  string my_file_id = year.ToString() + month.ToString() + day.ToString() + hour.ToString() + minute.ToString() + second.ToString() + millisecond.ToString()+iFile.ToString();

      fileName = System.IO.Path.GetFileName(postedFile.FileName);  fileExtension = System.IO.Path.GetExtension(fileName);  file_id = my_file_id+fileExtension;  if (fileName != "")  {   fileExtension = System.IO.Path.GetExtension(fileName);   strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");   strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");   strMsg.Append("上传文件的文件名:" + file_id + "<br>");   strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");   postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + file_id);  } } strStatus.Text = strMsg.ToString(); return true;}catch(System.Exception Ex){ strStatus.Text = Ex.Message; return false;}}


    最新回复(0)