且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用文件路径下载文件.

更新时间:2023-01-05 13:54:47

参考:
ContentType字符串,以便它指定适当的文件格式.该字符串的语法通常设置为类型/子类型",其中类型"是常规内容类别,子类型"是特定内容类型.有关受支持的内容类型的完整列表,请参阅Web浏览器文档或当前的HTTP规范.以下列表概述了一些常见的ContentType值:
文本/HTML"
图像/GIF"
图像/JPEG"
文字/纯文字"
应用程序/msword"(用于Microsoft Word文件)
应用程序/x-msexcel"(用于Microsoft Excel文件)

Ref:
ContentType string so that it specifies the appropriate file format. The syntax of this string is usually formatted as "type/subtype," where "type" is the general content category and "subtype" is the specific content type. For a full list of supported content types, refer to your Web browser documentation or the current HTTP specification. The following list outlines some common ContentType values:
"text/HTML"
"image/GIF"
"image/JPEG"
"text/plain"
"Application/msword" (for Microsoft Word files)
"Application/x-msexcel" (for Microsoft Excel files)

public DownloadContent(string ID)
{
  SqlConnection con;
   try
        {
 
                con = new SqlConnection();
                con.ConnectionString = "YourConn";
                con.Open();
    
    
            string query = "your query to retrieve from db where ID = ID"// assuming 1 record here";
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();
            
            if (dr.Read())
            {
                string path =Convert.ToString(dr[1]); //assuming second record on dr is the file path
                byte[] content = System.IO.File.ReadAllBytes(path); //you may have to modify path using Server.MapPath -> depend the on the filepath you stored.
                Response.ContentType = "Application/msword"//sent your content type here, see ref link
                Response.AddHeader("Content-Disposition", "attachment;filename=somename.doc");//set file type here.
                Context.Response.BinaryWrite(content);
    
    
            }
            cmd = null;
            dr.Close();
            con.Close();
        }
        catch (Exception ex)
        {
        }
       finally
       {
        if(con!= null)
         con.Close();
       }
}


我认为缺少的信息是这是一个Web应用程序.您需要将IIS配置为提供文件类型,然后可以将www.yourdomain.com替换为Web根目录的路径,以生成文件的URL.
I assume the missing bit of info is that this is a web app. Your IIS needs to be configured to serve the file type and you can replace the path to your web root with www.yourdomain.com to generate a URL to your file.