首页 > 编程语言 >C# 本地文件的上传和下载

C# 本地文件的上传和下载

时间:2023-12-08 10:57:52浏览次数:25  
标签:本地 C# Text file dt 上传 string row

本文主要介绍一下,在APS.NET中文件的简单上传于下载,上传是将文件上传到服务器的指定目录下,下载是从存入数据库中的路径,从服务器上下载。

  1.上传文件

  (1)页面代码

   <table align="center" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="right">文件名称:</td>
                    <td>
                        <asp:TextBox ID="FileName" runat="server"></asp:TextBox>
                    </td>
                    <td></td>
                </tr>  
                <tr>
                    <td align="right">浏览:</td>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td>
                    <td></td>
                </tr>   
                <tr>
                    <td></td>
                    <td>
                        <asp:Button ID="UploadButton" runat="server" Text="上传" 
                            onclick="UploadButton_Click" /><asp:Label ID="Msg" runat="server" ForeColor="#FF0000"></asp:Label>     
                    </td>
                    <td></td>
                </tr>               
        </table>

  (2).后台代码  

protected void UploadButton_Click(object sender, EventArgs e)
        {
            Msg.Text = "";
            MyWebSite.DAL.FileInfo file = new MyWebSite.DAL.FileInfo();
            if (string.IsNullOrEmpty(FileName.Text))
            {
                Msg.Text = "请输入文件名";
                return;
            }
            if (FileUpload1.HasFile)
            {
                try
                {

                    DateTime upload = DateTime.Now;
                    string flag = Path.GetExtension(FileUpload1.PostedFile.FileName);
                    string path = Server.MapPath("../Upload/" + FileUpload1.FileName);
                    string size = (FileUpload1.PostedFile.ContentLength / 1024).ToString();
                    FileUpload1.SaveAs(path);
                    file.FileName = FileName.Text.ToString();
                    file.Type = flag;//获得文件格式
                    file.Size = size;//文件大小
                    file.FilePath = path;//上传到服务器的绝对路径
                    file.UploadTime = DateTime.Now.ToShortDateString();//上传时间
                    handler.AddFile(file);//将上传的文件信息保存到数据库
                    Msg.Text = "上传成功!";
                }
                catch
                {

                    Msg.Text = "上传失败!";
                }
            }
        }

  2.下载文件

  (1)前台页面

<asp:Repeater ID="Repeater1" runat="server" onitemcommand="down_file_Click">
    <ItemTemplate>       
          <table width="90%" align="center" border="1" cellpadding="1" cellspacing="0" bgcolor="#e1e1e1" class="title_font">
           <tr>
                <td class="title_font" width="10%"  align="center">文件名称:</td>
                <td width="20%"align="center"><b><asp:Label ID="FileTitle" runat="server" Text='<%#Eval("文件名称") %>'></asp:Label></b></td>
                <td  width="6%"align="center">类型:</td>
                <td width="6%"align="center"><%#Eval("类型") %></td>                
                <td width="10%" align="center">文件大小:</td>
                <td  width="8%"align="center"><%#Eval("文件大小") %>KB</td>
                <td width="10%"align="center">上传时间:</td>
                <td ><%#Eval("上传时间") %></td>
                <td  width="10%" colspan="2" align="center"><asp:LinkButton ID="LinkButton1" CommandArgument='<%#Eval("link") %>' runat="server">下载文件</asp:LinkButton>
                </td>
            </tr>           
        </table>
        <br />
    </ItemTemplate>
</asp:Repeater>

  (2)后台代码

  1).绑定数据

        public void GrvDataBin(List<FileInfo> list)
        {

            DataView dv = new DataView();
            DataTable dt = new DataTable("fileMeta");
            {
                dt.Columns.Add("文件名称");
                dt.Columns.Add("类型");
                dt.Columns.Add("上传时间");
                dt.Columns.Add("文件大小");
                dt.Columns.Add("link");
            }
            foreach (FileInfo fileM in list)
            {
                DataRow row = dt.NewRow();
                row[0] = fileM.FileName;
                row[1] = fileM.Type;
                row[2] = fileM.UploadTime;
                row[3] = fileM.Size;
                row[4] = fileM.FilePath;
                dt.Rows.Add(row);
            }
            dv.Table = dt;
            Repeater1.DataSource = dv;
            Repeater1.DataBind();

        }

  2).下载文件

  

protected void down_file_Click(object sender, RepeaterCommandEventArgs e)
        {
            System.IO.FileStream fs = null;
            try
            {
                string filePath = e.CommandArgument.ToString();
                string fileName = ((Label)e.Item.FindControl("FileTitle")).Text.ToString();
                fs = System.IO.File.OpenRead(filePath);
                byte[] buffer = new byte[1024];
                long count = 1024;
                Response.Buffer = true;
                Response.AddHeader("Connection", "Keep-Alive");
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(System.IO.Path.GetFileName(filePath)));//下载时要保存的默认文件名
                Response.AddHeader("Content-Length", fs.Length.ToString());
                while (count == 1024)
                {
                    count = fs.Read(buffer, 0, 1024);
                    Response.BinaryWrite(buffer);
                }

            }
            catch (Exception ex)
            {
                return;
            }
            finally
            {
                fs.Close();
            }
        }

  以上就完成了,简单的文件上传与下载。 

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/08/c-%e6%9c%ac%e5%9c%b0%e6%96%87%e4%bb%b6%e7%9a%84%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论

 

 

标签:本地,C#,Text,file,dt,上传,string,row
From: https://www.cnblogs.com/songsu/p/17884670.html

相关文章

  • xcat docker部署使用
    已打包到docker镜像dockerpullleaus/xcat:2.14.6#softversion:2.14.6#osversion:centos7.6.1610本镜像仅适用于centos7以上系统,支持docker共用宿主机网络宿主机不能存在tftpd、dhcpd、httpd、chronyd服务,否则可能会导致xcat启动失败宿主机免密码登录(已有可跳过)ssh......
  • 【Docker】更改docker镜像的存储路径
    1.查看Docker存储路径dockerinfo|grep"DockerRootDir"2.关闭所有运行的容器···dockerps|awk'{print$1}'|xargsdockerstop···3.停止docker服务systemctlstopdocker4.新增的磁盘挂载点上新建目录,并将原有的docker容器和镜像全部拷贝过来,比如这里新增......
  • EMMC、Uboot操作命令
    ​MMC相关命令​编辑​编辑FAT格式文件系统操作命令存储器的分类整理(SRAM/DRAM/NORFLASH/NandFLASH)_norflashsram-CSDN博客fatinfo查询MMC设备分区的文件系统信息fatinfommc1:1fatls查询FAT格式设备的目录和文件信息fatlsmmc1:1fstype 用于查看MMC设备......
  • A Novel Approach Based on Bipartite Network Recommendation and KATZ Model to Pre
    ANovelApproachBasedonBipartiteNetworkRecommendationandKATZModeltoPredictPotentialMicro-DiseaseAssociationsShiruLi 1, MinzhuXie 1, XinqiuLiu 2Affiliations expandPMID: 31803235 PMCID: PMC6873782 DOI: 10.3389/fgene.2019......
  • C# ListView失去焦点仍然保持选中的Item高亮
    1privatevoidlistView_Validated(objectsender,EventArgse)2{3if(listView.FocusedItem!=null)4{5listView.FocusedItem.BackColor=SystemColors.Highlight;6listView.FocusedItem.ForeColor=Color.White;......
  • A novel essential protein identification method based on PPI networks and gene e
    AnovelessentialproteinidentificationmethodbasedonPPInetworksandgeneexpressiondataJianchengZhong 1 2, ChaoTang 1, WeiPeng 3, MinzhuXie 1, YusuiSun 1, QiangTang 4, QiuXiao 5, JiahongYang 6Affiliations expandPMID:......
  • count(*),count(1),count(字段)
    为什么阿里巴巴禁止使用count(列名)或count(常量)来替代count(*)-阿里云开发者社区(aliyun.com)1.关于数据库中统计行数,无论是MySQL还是Oracle,都有只有一个函数可以使用,就是countcount(*):统计的结果中,包含值为NULL的行数,count(1):统计的结果中,包含值为NULL的行数count(字段)......
  • xcat注入驱动,添加raid卡或网卡驱动
    创建额外配置文件chdef-tosimagecentos7.3-x86_64-install-compute-SN850imagetype=linuxosarch=x86_64osdistroname=centos7.3-x86_64osname=Linuxosvers=centos7.3otherpkgdir=/install/post/otherpkgs/centos7.3/x86_64pkgdir=/install/centos7.3/x86_64pkglist=/o......
  • 界面控件DevExpress中文教程 - 如何用Office File API组件填充PDF表单
    DevExpressOfficeFileAPI是一个专为C#,VB.NET和ASP.NET等开发人员提供的非可视化.NET库。有了这个库,不用安装MicrosoftOffice,就可以完全自动处理Excel、Word等文档。开发人员使用一个非常易于操作的API就可以生成XLS,XLSx,DOC,DOCx,RTF,CSV和SnapReport等企业级文......
  • Amazon CodeWhisperer 开箱初体验
    文章作者:Coder9527科技的进步日新月异,正当人工智能发展如火如荼的时候,各大厂商在“解放”码农的道路上不断创造出各种Coding利器,今天在下就带大家开箱体验一个Coding利器: AmazonCodeWhisperer。亚马逊云科技开发者社区为开发者们提供全球的开发技术资源。这里有技术文档、......