通过api 下载sharepoint 文件

说明

通过api 下载SharePoint 中的文件,需要通过get 方式进行请求,需要配置有权限下载文件的sharepoint账号密码,拿到文件流,然后会跳转到一个空白页面进行下载,只要配置账号密码,下载的时候就不会在需要登录了。

/// <summary>
        /// 得到所有数据
        /// </summary>
        /// <returns>返回数据</returns>
        [HttpGet, Route("api/User/FileDown")]
        [AllowAnonymous]
        public HttpResponseMessage FileDown(string filename)
        {
            
            const string username = "账号";
            const string password = "密码";
             string url = filename; //文件地址:https://***.cn/cs/cwtest/111/20201111175902.docx
            var securedPassword = new SecureString();
            foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
            var credentials = new SharePointOnlineCredentials(username, securedPassword); 
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            using (var client = new WebClient())
            {
                client.Credentials = credentials;
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
               var  entity = client.OpenRead(url); 
                response.Content = new StreamContent(entity);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                //文件名称,这里可以通过截取上面的文件url 地址中的文件名
                    FileName = "20201111175902.docx"
                };
            }
           
            return response;
        }
Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐