如何以编程方式从sharepoint文档库下载文件

时间:2011-07-07 09:13:29

标签: sharepoint sharepoint-2007

在按钮单击事件或单击链接按钮上,我想从sharepoint文档库下载文档并将其保存到用户的本地磁盘。

Plz帮助我,如果您有任何代码示例,请分享

2 个答案:

答案 0 :(得分:4)

输出到文件的直接链接的问题是,对于某些内容类型,它可能只是在浏览器窗口中打开。如果这不是理想的结果,并且您想要强制保存文件对话框,则需要编写一个ASP / PHP页面,您可以通过查询字符串传递文件名。然后,此页面可以读取文件并在响应上设置一些标题,以指示内容处置是和附件。

对于ASP.net,如果您创建一个名为download.aspx的简单aspx页面,请将以下代码添加到其中,然后将此文件放在服务器的某个位置,您可以通过调用此页面来下载文件:

http://yourserveraddress/download.aspx?path=http://yoursharepointserver/pathtodoclibrary/file.ext

protected void Page_Load(object sender, EventArgs e)
    {
        string path = "";
        string fileName = "";

        path = Request.QueryString["path"];
        if (path != null && path.Length > 0)
        {
            int lastIndex = path.LastIndexOf("/");
            fileName = path.Substring(lastIndex + 1, (path.Length - lastIndex - 1));

            byte[] data;
            data = GetDataFromURL(path);

            Response.Clear();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(data);
            Response.Flush();
        }
    }


    protected byte[] GetDataFromURL(string url)
    {
        WebRequest request = WebRequest.Create(url);
        byte[] result;
        byte[] buffer = new byte[4096];

        //uncomment this line if you need to be authenticated to get to the files on SP
        //request.Credentials = new NetworkCredential("username", "password", "domain");

        using (WebResponse response = request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = responseStream.Read(buffer, 0, buffer.Length);
                        ms.Write(buffer, 0, count);
                    } while (count != 0);
                    result = ms.ToArray();
                }
            }
        }
        return result;
    }

答案 1 :(得分:0)

我创建一个LinkBut​​ton并以编程方式将URL设置为文档的URL。