• WEB文件上传下载功能


    WEB文件上传下载在日常工作中经常用到的功能

    这里用到JS库

    http://files.cnblogs.com/meilibao/ajaxupload.3.5.js

    上传代码段(HTML)

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UrlTest.aspx.cs" Inherits="WebDome.UrlTest" %>

    <!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 src="../../scripts/ajaxupload.3.5.js" type="text/javascript"></script>

    <script type="text/javascript">     

         $(function () {          

        var btnUpload = $('#lblFile');        

          var status = $('#lblstatus');

          new AjaxUpload(btnUpload, {    

                  action: '/Upload.aspx',        

                  name: 'txtFile',          

                  onSubmit: function (file, ext) {             

                   if (!(ext && /^(xls|doc|xlsx|docx|pdf|swf|zip|rar)$/.test(ext))) {          

                    status.text('温馨提示:只能上传Excel、Word、PDF,ZIP,RAR或者SWF文件。');      

                    return false;               

                    }                     

                  status.text('正在上传,请稍候...');                 

                  },                 

                 onComplete: function (file, response) {              

                     status.text('');                     

                     $("#hdFilePath").val('');                     

                      var c = response.substring(0, 2);                     

                      var t = response.substring(3);                     

                      if (c === "00") {                         

                         status.text('上传成功。文件名称:' + response.substring(70));                         

                        $("#hdFilePath").val(response.substring(15));                     

                       } else {                         

                               status.text(t);                     

                       }                 

                      }             

                   });         

                });    

         </script>

    </head>

    <body>

        <form id="form1" runat="server">    

       <div>   

        </div>   

      </form>

    </body>

    </html>

    ---下面是Upload.aspx处理上传文件

     protected void Page_Load(object sender, EventArgs e)    

              {        

                  try        

                     {            

                      string sPath = "/UploadFile/" + DateTime.Now.ToString("yyyyMMdd") + @"" + CurrentAdmin.OpId + @"";

                      string path = Server.MapPath(sPath);            

                     if (!Directory.Exists(path))            

                       {                

                            Directory.CreateDirectory(path);            

                       }            

                      HttpPostedFile hpfFile = Request.Files["txtFile"];

                     if (hpfFile.ContentLength == 0)                

                       throw new Exception("文件大小为0字节,上传文件失败!");

                string extendName = hpfFile.FileName.Substring(hpfFile.FileName.LastIndexOf("."));

                string tempFileName = Guid.NewGuid().ToString() + "_" + hpfFile.FileName.Substring(0, hpfFile.FileName.LastIndexOf("."));

                hpfFile.SaveAs(path + tempFileName + extendName);

                Response.Write("00|" + sPath + tempFileName + extendName);        

              }   catch (Exception ex)        

             {            

               Response.Write("02|" + ex.Message);        

            }    

    }

    --上传文件END---

    下载文件

    页面HTML

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileDownload.aspx.cs" Inherits="WebDome.FileDownload" %>

    <!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> </head> <body>     <form id="form1" runat="server">     <div>      

              &nbsp;<asp:LinkButton ID="lkbtnDownload"            

              CommandArgument="/UploadFile/<%=fileName%>" runat="server"  

              style=" text-decoration:none;color:Black;" onclick="lkbtnDownload_Click">LinkButton</asp:LinkButton>

        </div>     </form> </body> </html>

    ---DownLoad--Method

    public static void DownLoadFile(System.Web.UI.WebControls.LinkButton LinkButton1, System.Web.UI.Page page)
            {
                string filePath = page.Server.MapPath(LinkButton1.CommandArgument as string);
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
                string fileName = fileInfo.Name;
                string fileextend = fileInfo.Extension;
                string contentType = "";
                if (fileextend == ".xls")
                    contentType = "application/vnd.ms-excel";
                if (fileextend == ".xlsx")
                    contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                if (fileextend == ".doc")
                    contentType = "application/msword";
                if (fileextend == ".docx")
                    contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                if (fileextend == ".pdf")
                    contentType = "application/pdf";
                if (fileextend == ".swf")
                    contentType = "application/x-shockwave-flash";
                page.Response.Clear();
                page.Response.ClearContent();
                page.Response.ClearHeaders();
                page.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName.Substring(37), System.Text.Encoding.UTF8));
                page.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                page.Response.AddHeader("Content-Transfer-Encoding", "binary");
                page.Response.ContentType = contentType;
                page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                page.Response.WriteFile(fileInfo.FullName);
                page.Response.Flush();
                page.Response.Close();
            }

    搞定--------------------

  • 相关阅读:
    【第4题】 什么是https
    【第3题】 两个队列生成一个栈
    【第2题】 链表的逆置
    【第1题】 Pythonn内存管理以及垃圾回收机制
    tmunx error:invalid option: status-utf8 invalid option: utf8
    ubuntu install google-chrome-stable
    使用pyenv安装多个Python版本
    Linux命令行烧录树莓派镜像至SD卡
    freenode configuration sasl authentication in weechat
    尝试IRC & freenode
  • 原文地址:https://www.cnblogs.com/meilibao/p/3472692.html
Copyright © 2020-2023  润新知