[英]How do I return a document from a Sharepoint Document library to the user?
[英]Download from SharePoint Document Library without having user login
我正在尝试从ASP.NET应用程序从Sharepoint文档库下载文件。 我能够获得文件列表,但是当我使用相同的上下文进行下载时,出现了(401)未经授权的错误。 问题类似于此问题,但是由于我试图在没有用户登录的情况下下载文件,因此没有用户名和密码。 我的代码如下:
using (var ctx = TokenHelper.GetClientContextWithAccessToken(ConfigurationManager.AppSettings("url"), TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken) )
{
var web = ctx.Web;
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(fromLocation);
ctx.Load(file);
ctx.ExecuteQuery();
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
using (var ms = new MemoryStream())
{
fileInfo.Stream.CopyTo(ms);
return ms.ToArray();
}
}
似乎您使用的是提供商托管的应用程序(如果是),是否设置了从指定文档库读取的应用程序权限?
您也可以检查ULS日志并搜索401文本,以查看尝试下载文档的身份出了什么问题
通过从文件获取流。 我能够将其转换为字节数组并对其进行调用二进制写入,而不必使用OpenBinaryDirect并处理身份验证问题
using (var ctx = TokenHelper.GetClientContextWithAccessToken(ConfigurationManager.AppSettings("url"), TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken) )
{
var web = ctx.Web;
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(fromLocation);
ClientResult(Of Stream) data = file.OpenBinaryStream();
ctx.Load(file);
ctx.ExecuteQuery();
HttpContext.Current.Response.ContentType = MimeMapping.GetMimeMapping(file.Name);
HttpContext.Current.Response.AppendHeader("content-disposition", "inline;filename=" + file.Name);
HttpContext.Current.Response.AppendHeader("content-length", data.Value.Length.ToString());
HttpContext.Current.Response.BinaryWrite(StreamToByteArray(data.Value));
HttpContext.Current.Response.Flush();
}
private byte[] StreamToByteArray(ByVal input As Stream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
我与此有关的一个问题是大文件。 使用OpenBinaryStream代替OpenBinaryDirect意味着需要一段时间才能加载文件,然后才能开始下载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.