上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端

文件操作应用场景:

如果你的.NET项目是运行在SharePoint服务器上的,你可以直接使用SharePoint服务器端对象模型,用SPFileCollection.Add方法

http://msdn.microsoft.com/zh-cn/library/ms454491%28office.12%29.aspx

如果不在同一台机器上,并且你的SharePoint是2010,你可以使用.NET客户端对象模型,用FileCollection.Add方法

http://msdn.microsoft.com/zh-cn/library/microsoft.sharepoint.client.filecollection.add(en-us).aspx

如果是SharePoint 2007,你可以用SharePoint Web Service里面的copy.asmx

http://msdn.microsoft.com/zh-cn/library/copy.copy_members%28en-us,office.12%29.aspx

============帮助文档说明===========

Create Author: Kenmu

Create Date: 2014-05-22

Function: 支持上传文件到Sharepoint的文档库中;下载Sharepoint的文档库的文件到客户端

Support three ways as following:

1)通过调用SharePoint的Copy.asmx服务实现;只适用于SharePoint站点

IFileOperation fileOperation = new SPServiceOperation();

bool isSuccess = fileOperation.UploadFileToSPSite(domain, userAccount, pwd, documentLibraryUrl, localFilePath, ref statusInfo);

bool isSuccess = fileOperation.DownloadFileFromSPSite(domain, userAccount, pwd, documentUrl, downloadToLocalFilePath, ref statusInfo);

2)通过WebClient实现;适用于普通站点

IFileOperation fileOperation = new WebClientOperation();

3)通过WebRequest实现;适用于普通站点

IFileOperation fileOperation = new WebRequestOperation();


关键代码: 

IFileOperation.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5
 6 namespace FileOperationAboutSharePoint.FileOperation
 7 {
 8     interface IFileOperation
 9     {
10         bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath,ref string statusInfo);
11         bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo);
12     }
13 }

SPServiceOperation.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.IO;
 6 using System.Net;
 7 using FileOperationAboutSharePoint.SPCopyService;
 8
 9 namespace FileOperationAboutSharePoint.FileOperation
10 {
11     public class SPServiceOperation : IFileOperation
12     {
13         public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
14         {
15             bool isSuccess = false;
16             try
17             {
18                 string fileName = Path.GetFileName(localFilePath);
19                 string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
20                 File.Copy(localFilePath, tempFilePath, true);
21                 FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
22                 BinaryReader br = new BinaryReader(fs);
23                 byte[] fileContent = br.ReadBytes((int)fs.Length);
24                 br.Close();
25                 fs.Close();
26                 Copy service = CreateCopy(domain, userAccount, pwd);
27                 service.Timeout = System.Threading.Timeout.Infinite;
28                 FieldInformation fieldInfo = new FieldInformation();
29                 FieldInformation[] fieldInfoArr = { fieldInfo };
30                 CopyResult[] resultArr;
31                 service.CopyIntoItems(
32                     tempFilePath,
33                     new string[] { string.Format("{0}{1}", documentLibraryUrl, fileName) },
34                     fieldInfoArr,
35                     fileContent,
36                     out resultArr);
37                 isSuccess = resultArr[0].ErrorCode == CopyErrorCode.Success;
38                 if (!isSuccess)
39                 {
40                     statusInfo = string.Format("Failed Info: {0}", resultArr[0].ErrorMessage);
41                 }
42
43             }
44             catch (Exception ex)
45             {
46                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
47                 isSuccess = false;
48             }
49             return isSuccess;
50         }
51
52         public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
53         {
54             bool isSuccess = false;
55             try
56             {
57                 Copy service = CreateCopy(domain, userAccount, pwd);
58                 service.Timeout = System.Threading.Timeout.Infinite;
59                 FieldInformation[] fieldInfoArr;
60                 byte[] fileContent;
61                 service.GetItem(documentUrl,out fieldInfoArr,out fileContent);
62                 if (fileContent != null)
63                 {
64                     FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
65                     fs.Write(fileContent, 0, fileContent.Length);
66                     fs.Close();
67                     isSuccess = true;
68                 }
69                 else
70                 {
71                     statusInfo = string.Format("Failed Info: {0}不存在", documentUrl);
72                     isSuccess = false;
73                 }
74             }
75             catch (Exception ex)
76             {
77                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
78                 isSuccess = false;
79             }
80             return isSuccess;
81         }
82
83         private Copy CreateCopy(string domain, string userAccount, string pwd)
84         {
85             Copy service = new Copy();
86             if (String.IsNullOrEmpty(userAccount))
87             {
88                 service.UseDefaultCredentials = true;
89             }
90             else
91             {
92                 service.Credentials = new NetworkCredential(userAccount, pwd, domain);
93             }
94             return service;
95         }
96     }
97 }

WebClientOperation.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.IO;
 6 using System.Net;
 7
 8 namespace FileOperationAboutSharePoint.FileOperation
 9 {
10     public class WebClientOperation : IFileOperation
11     {
12         public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
13         {
14             bool isSuccess = false;
15             try
16             {
17                 string fileName = Path.GetFileName(localFilePath);
18                 string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
19                 File.Copy(localFilePath, tempFilePath, true);
20                 FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
21                 BinaryReader br = new BinaryReader(fs);
22                 byte[] fileContent = br.ReadBytes((int)fs.Length);
23                 br.Close();
24                 fs.Close();
25                 WebClient webClient = CreateWebClient(domain, userAccount, pwd);
26                 webClient.UploadData(string.Format("{0}{1}", documentLibraryUrl, fileName), "PUT", fileContent);
27                 isSuccess = true;
28             }
29             catch (Exception ex)
30             {
31                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
32                 isSuccess = false;
33             }
34             return isSuccess;
35         }
36
37         public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
38         {
39             bool isSuccess = false;
40             try
41             {
42                 WebClient webClient = CreateWebClient(domain, userAccount, pwd);
43                 byte[] fileContent = webClient.DownloadData(documentUrl);
44                 FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
45                 fs.Write(fileContent, 0, fileContent.Length);
46                 fs.Close();
47             }
48             catch (Exception ex)
49             {
50                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
51                 isSuccess = false;
52             }
53             return isSuccess;
54         }
55
56         private WebClient CreateWebClient(string domain, string userAccount, string pwd)
57         {
58             WebClient webClient = new WebClient();
59             if (String.IsNullOrEmpty(userAccount))
60             {
61                 webClient.UseDefaultCredentials = true;
62             }
63             else
64             {
65                 webClient.Credentials = new NetworkCredential(userAccount, pwd, domain);
66             }
67             return webClient;
68         }
69     }
70 }

WebRequestOperation.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.IO;
 6 using System.Net;
 7
 8 namespace FileOperationAboutSharePoint.FileOperation
 9 {
10     public class WebRequestOperation : IFileOperation
11     {
12         public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
13         {
14             bool isSuccess = false;
15             try
16             {
17                 string fileName = Path.GetFileName(localFilePath);
18                 string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
19                 File.Copy(localFilePath, tempFilePath, true);
20                 FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
21                 BinaryReader br = new BinaryReader(fs);
22                 byte[] fileContent = br.ReadBytes((int)fs.Length);
23                 br.Close();
24                 fs.Close();
25                 MemoryStream ms = new MemoryStream(fileContent);
26                 WebRequest webRequest = CreateWebRequest(domain,userAccount,pwd,string.Format("{0}{1}", documentLibraryUrl, fileName));
27                 webRequest.Method = "PUT";
28                 webRequest.Headers.Add("Overwrite", "T");
29                 webRequest.Timeout = System.Threading.Timeout.Infinite;
30                 Stream outStream = webRequest.GetRequestStream();
31                 byte[] buffer = new byte[1024];
32                 while (true)
33                 {
34                     int i = ms.Read(buffer, 0, buffer.Length);
35                     if (i <= 0)
36                         break;
37                     outStream.Write(buffer, 0, i);
38                 }
39                 ms.Close();
40                 outStream.Close();
41                 webRequest.GetResponse();
42                 isSuccess = true;
43             }
44             catch (Exception ex)
45             {
46                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
47                 isSuccess = false;
48             }
49             return isSuccess;
50         }
51
52         public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
53         {
54             bool isSuccess = false;
55             try
56             {
57                 WebRequest webRequest = CreateWebRequest(domain, userAccount, pwd, documentUrl);
58                 webRequest.Method = "GET";
59                 webRequest.Timeout = System.Threading.Timeout.Infinite;
60                 using (Stream stream = webRequest.GetResponse().GetResponseStream())
61                 {
62                     using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
63                     {
64                         byte[] buffer = new byte[1024];
65                         int i = 1;
66                         while (i > 0)
67                         {
68                             i = stream.Read(buffer, 0, buffer.Length);
69                             fs.Write(buffer, 0, i);
70                         }
71                     }
72                 }
73                 isSuccess = true;
74             }
75             catch (Exception ex)
76             {
77                 statusInfo = string.Format("Failed Info: {0}", ex.Message);
78                 isSuccess = false;
79             }
80             return isSuccess;
81         }
82
83         private WebRequest CreateWebRequest(string domain, string userAccount, string pwd, string requestUriString)
84         {
85             WebRequest webRequest = WebRequest.Create(requestUriString);
86             if (String.IsNullOrEmpty(userAccount))
87             {
88                 webRequest.UseDefaultCredentials = true;
89             }
90             else
91             {
92                 webRequest.Credentials = new NetworkCredential(userAccount, pwd, domain);
93             }
94             return webRequest;
95         }
96     }
97 }

Web.config

 1 <?xml version="1.0"?>
 2 <configuration>
 3   <configSections>
 4     <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
 5       <section name="FileOperationAboutSharePoint.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 6     </sectionGroup>
 7   </configSections>
 8
 9   <system.web>
10     <compilation debug="true" targetFramework="4.0" />
11     <authentication mode="Windows">
12     </authentication>
13   </system.web>
14
15   <system.webServer>
16      <modules runAllManagedModulesForAllRequests="true"/>
17   </system.webServer>
18   <system.serviceModel>
19     <bindings />
20     <client />
21   </system.serviceModel>
22   <applicationSettings>
23     <FileOperationAboutSharePoint.Properties.Settings>
24       <setting name="FileOperationAboutSharePoint_SPCopyService_Copy"
25         serializeAs="String">
26         <value>http://ifca-psserver/_vti_bin/copy.asmx</value>
27       </setting>
28     </FileOperationAboutSharePoint.Properties.Settings>
29   </applicationSettings>
30   <appSettings>
31     <add key="domain" value="IFCA"/>
32     <add key="userAccount" value="huangjianwu"/>
33     <add key="pwd" value="ifca.123456"/>
34     <add key="documentLibraryUrl" value="http://ifca-psserver/KDIT/"/>
35     <add key="downloadFileName" value="提示信息Message说明文档.docx"/>
36     <add key="downloadToLocalFilePath" value="C:\\Users\Administrator\Desktop\download_提示信息Message说明文档.docx"/>
37   </appSettings>
38 </configuration>

Default.aspx

上传操作:<asp:FileUpload ID="fuSelectFile" runat="server" />

<asp:Button ID="btnUpload" Text="上传" runat="server" Style="margin: 0 10px;" OnClick="btnUpload_Click" /><br />

下载操作:“<%= string.Format("{0}{1}",documentLibraryUrl, downloadFileName)%>”文件

<asp:Button ID="btnDownload" Text="下载" runat="server" Style="margin: 5px 10px;" OnClick="btnDownload_Click" />

<p /><strong>执行结果:</strong><br />

<asp:Literal ID="ltrInfo" runat="server"></asp:Literal>

Default.aspx.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using FileOperationAboutSharePoint.FileOperation;
 8 using System.Web.Configuration;
 9
10 namespace FileOperationAboutSharePoint
11 {
12     public partial class _Default : System.Web.UI.Page
13     {
14         private string domain = WebConfigurationManager.AppSettings["domain"];
15         private string userAccount = WebConfigurationManager.AppSettings["userAccount"];
16         private string pwd = WebConfigurationManager.AppSettings["pwd"];
17         protected string documentLibraryUrl = WebConfigurationManager.AppSettings["documentLibraryUrl"];
18         protected string downloadFileName = WebConfigurationManager.AppSettings["downloadFileName"];
19         private string downloadToLocalFilePath = WebConfigurationManager.AppSettings["downloadToLocalFilePath"];
20
21         protected void Page_Load(object sender, EventArgs e)
22         {
23
24         }
25
26         protected void btnUpload_Click(object sender, EventArgs e)
27         {
28             if (fuSelectFile.HasFile)
29             {
30
31                 string localFilePath = string.Format("{0}\\{1}", Server.MapPath("Upload"), fuSelectFile.PostedFile.FileName);
32                 fuSelectFile.PostedFile.SaveAs(localFilePath);
33                 string statusInfo = "";
34                 //IFileOperation fileOperation = new WebClientOperation();
35                 //IFileOperation fileOperation = new WebRequestOperation();
36                 IFileOperation fileOperation = new SPServiceOperation();
37                 bool isSuccess = fileOperation.UploadFileToSPSite(domain, userAccount, pwd, documentLibraryUrl, localFilePath, ref statusInfo);
38                 ltrInfo.Text = isSuccess ? "上传成功" : statusInfo;
39             }
40             else
41             {
42                 ltrInfo.Text = "请选择需要上传的文件";
43             }
44         }
45
46         protected void btnDownload_Click(object sender, EventArgs e)
47         {
48             string statusInfo = "";
49             //IFileOperation fileOperation = new WebClientOperation();
50             //IFileOperation fileOperation = new WebRequestOperation();
51             IFileOperation fileOperation = new SPServiceOperation();
52             bool isSuccess = fileOperation.DownloadFileFromSPSite(domain, userAccount, pwd, string.Format("{0}{1}", documentLibraryUrl, downloadFileName), downloadToLocalFilePath, ref statusInfo);
53             ltrInfo.Text = isSuccess ? string.Format("下载成功<br/>下载文件位置为:{0}", downloadToLocalFilePath) : statusInfo;
54         }
55     }
56 }

结果:

PS:如用第一种方式,就得在Visual Studio中添加Web Service,服务来源,例如:

http://ifca-psserver/_vti_bin/copy.asmx

时间: 2024-10-13 03:45:14

上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端的相关文章

本地开发spark代码上传spark集群服务并运行(基于spark官网文档)

打开IDEA 在src下的main下的scala下右击创建一个scala类 名字为SimpleApp ,内容如下 import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ import org.apache.spark.SparkConf object SimpleApp { def main(args: Array[String]) { val logFile = "/home/spark/opt/s

官方demo修改后的webuploader上传预览图片(兼容IE8) github下载回来的有问题

注意!!!!! 不要使用GitHub上下载回来的webuploader.js,下载回来的webuploader.js会报错  fn 未定义 方便的话去看百度官网的demo 浏览器将其抓包获取webuploader.js文件 <!DOCTYPE html> <html lang="zh-CN"> <head>     <meta charset="UTF-8">     <title>WebUploader演

npm包的上传npm包的步骤,与更新和下载步骤

官网: ======================================================= 没有账号可以先注册一个,右上角点击"Sign Up",有账号直接点击"Login" 注册与登录账号这些就不详说了,不懂直接重新学习吧!!!!!!!!======================================================= 打开终端:win+r 登录命令:npm login查找用户名命令:npm whoami==

SWFUpload多文件上传 文件数限制 setStats()

使用swfupload仿公平图片上传 SWFUpload它是基于flash与javascript的client文件上传组件. handlers.js文件 完毕文件入列队(fileQueued) → 完毕选择文件(fileDialogComplete) → 開始上传文件(uploadStart) → 上传处理(uploadProgress) → 上传成功(uploadSuccess) → 上传完毕(uploadComplete)  → 列队完毕(queueComplete) 如上所看到的.单选文件

配置允许匿名用户登录访问vsftpd服务,进行文档的上传下载、文档的新建删除等操作

这里在centos7版本系统下验证的. 一般情况下,匿名用户的上传下载,所使用的用户都是ftp用户的权限:若要上传文件,则需要ftp用户对文件有w的权限,若要下载,则需要ftp用户对文件有r的权限. 步骤 修改配置文件vsftpd.conf(根据需要配置)# vim /etc/vsftpd/vsftpd.conf    anonymous_enable=YES                  #是否允许匿名用户登录    write_enable=YES                    

jsp文件上传

整理了一下jsp的上传下载,由客户端到服务端,包括一些常规的业务 一客户端 先看最基本的情况 1 在表单设置multipart/form-data,通过提交键把数据和附件一次性提交的.服务器更多的是对应这个例子. 但有以下问题 一般的Ajax无法把附件数据发过去 附件往往涉及比较多问题,比如上传需要时间(要有个进度),上传也有可能不成功等,上传需要校验的东西就比较多. 2于是就有把上传分开来自己执行的.上传项在浏览文件后就开始上传,其他表单数据在提交表单时再提交. 更详细地说是:上传在表单中有自

jquery插件--ajaxfileupload.js上传文件原理分析

英文注解应该是原作者写的吧~说实话,有些if判断里的东西我也没太弄明白,但是大致思路还是OK的. jQuery.extend({ createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数 //create frame var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id var iframeHtml = '<iframe id="' + f

文件上传利器SWFUpload使用指南

SWFUpload是一个flash和js相结合而成的文件上传插件,其功能非常强大.以前在项目中用过几次,但它的配置参数太多了,用过后就忘记怎么用了,到以后要用时又得到官网上看它的文档,真是太烦了.所以索性就把它的用法记录下来,也方便英语拙计的同学查看,利人利己,一劳永逸. SWFUpload的特点: 1.用flash进行上传,页面无刷新,且可自定义Flash按钮的样式; 2.可以在浏览器端就对要上传的文件进行限制; 3.允许一次上传多个文件,但会有一个上传队列,队列里文件的上传是逐个进行的,服务

jfinal初接触,一个简单的文件上传例子

写了个上传的小例子. 从jfinal官网下载jfinal-1.8_demo_for_jsp.zip 然后下载jfinal-1.8-lib.zip 按要求删掉该删除的,引入一些包,之后的项目结构: DemoConfig.java中配置路由,只留下了根路径: /** * 配置路由 */ public void configRoute(Routes me) { me.add("/", CommonController.class); //me.add("/blog", B