How to Programatically Download files from sharepoint document library

一世执手 提交于 2019-12-10 13:58:12

问题


On button click event or on Link button click, I want to download document from sharepoint document library and save it to the user's local disk.

Plz help me on this,If you have any code sample then please share


回答1:


The problem with outputting a direct link to the file, is that for some content types it may just open in the browser window. If that is not the desired outcome, and you want to force the save file dialog, you'll need to write an ASP/PHP page that you could pass a filename to via the querystring. This page could then read the file and set some headers on the response to indicate that the content-disposition is and attachment.

For ASP.net, if you create a simple aspx page called download.aspx, add the following code into it, then put this file on a server somewhere you can download files by calling this page like this:

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;
    }



回答2:


I'd create a LinkButton and set the URL to the document's url programmatically.



来源:https://stackoverflow.com/questions/6608317/how-to-programatically-download-files-from-sharepoint-document-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!