在asp.net页面中读取数据库里的文件存放路径,提供下载功能。

2022-08-20 综合 113阅读

嗯文下载很重要呀,最近两天都看见了,首先先占时间稍后补上一切。。。

呵呵经过不懈的努力终于搞定了。。。。不多说了代码如下:

 FileInofr类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
///
/// FileInofr 的摘要说明
///

public class FileInofr
{
    public static bool DownLoadFile(string url)
    {
        var flag = false;
        try
        {
            var filePath = HttpContext.Current.Server.MapPath(url);     //获取文件的路径
            var file = new FileInfo(filePath);  //得到文件
            if (file.Exists)        //判断文件是否存在
            {
                HttpContext.Current.Response.Clear();       //清空Response对象
                /*设置浏览器请求头信息*/
                HttpContext.Current.Response.AddHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(file.Name));  //指定文件
                HttpContext.Current.Response.AddHeader("Content-Length",file.Length.ToString());    //指定文件大小
                HttpContext.Current.Response.ContentType = "application/application/octet-stream";  //指定输出方式
                HttpContext.Current.Response.WriteFile(file.FullName);      //写出文件
                HttpContext.Current.Response.End();         //结束Response对象
                HttpContext.Current.Response.Flush();       //输出缓冲区(刷新Response对象)
                HttpContext.Current.Response.Clear();       //清空Response对象
                                                                        
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception)
        {
            flag = false;
        }
        return flag;
    }
}

在页面中的使用:

DownLoadFile.aspx页面中的.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class DownLoadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {   /*在这里,我只测试两个文件*/
            //var path = "UpLoadFiles/" + "test.cs";
            var path = "UpLoadFiles"+"Contracts.devlab9ts.msi";     //这里不能使用物理路径
            FileInofr.DownLoadFile(path);
        }
    }
}


声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com