使用文件路径下载文件. [英] Download Files Using File Paths.
本文介绍了使用文件路径下载文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将文件详细信息存储在数据库中,并已在gridview中成功显示了文件详细信息(名称,上传日期等),但是我还有一个下载按钮(按钮类型为链接),该按钮应该能够下载文件.文件路径存储在数据库中,而文件存储在目录中.请问我如何使用数据库中的文件路径下载文件.任何代码
谢谢
I have stored the file details in a database and have successfully displayed the files details(name,upload date uploaded by etc) in a gridview.However i also have a download button(button type is link) which should be able to downlaod the file.The file paths are stored in the database whereas the files are stored in a directory.Can some how i use the files path from the Database to download files..any codes
Thanks
推荐答案
参考:
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.
这篇关于使用文件路径下载文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文