之前有个Project 要求上传文件至Sharepint Site 中的 Document Library ,先后用两种方法处理:
1,直接使用主程序代码,但却必须放在SharePoint Server 上执行才能成功;
2,使用Web Service 方法,主程序即可随意放在那台PC 中均可调用执行上传动作。
先是使用方法1成功,但在改为方法2时,出现了问题,总是执行不成功。
原因及解决方法:
经过多方面的检查及上网Google ,最终发现竟然是由于缺少了一个设定,参看以下红色字体的代码,对SPWeb 设定:
web.AllowUnsafeUpdates = true;
但是在之前主程序中调用时,无需此设定也可以成功,当然仍然缺少不了绿色部分的代码,对SPSite 设定:
site.AllowUnsafeUpdates = true;
看来为安全起见,以后处理时,还是两处代码均需要写上才行。绿色部分的代码在一般的更新字段值的情况足以处理,但此次经验却发现有时还是需要设定 SPSite 级别的 AllowUnsafeUpdates = true 才行。
代码如下:
/// 真实使用,传入指定的 SPS Server URL / Doc Lib URL / Doc Name / Doc Binary Array
[WebMethod]
public bool UploadDocument(string p_sServer_URL,
string p_sDocLib_URL,
string p_sDocName,
Byte[] p_DocBinaryArray)
{
bool result = false;
SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
site = new SPSite(p_sServer_URL);
site.AllowUnsafeUpdates = true;
web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
}
);
SPFolder sp_folder = web.GetFolder(p_sDocLib_URL);
if (sp_folder.Exists)
{
sp_folder.Files.Add(p_sDocName, p_DocBinaryArray, true); // overwrite if exists
sp_folder.Update();
result = true;
}
else
{
result = false;
}
}
catch (Exception ex)
{
result = false;
}
finally
{
site.Close();
site.Dispose();
web.Close();
web.Dispose();
}
return result;
}
/// 本地测试使用,传入指定的 SPS Server URL / Doc Lib URL / Doc Name / 真接打开本地文件,并产生 Doc Binary Array
//[WebMethod]
public bool UploadDocument_LocalTest(string p_sServer_URL,
string p_sDocLib_URL,
string p_sDocName)
{
bool result = false;
SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
site = new SPSite(p_sServer_URL);
web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
}
);
SPFolder sp_folder = web.GetFolder(p_sDocLib_URL);
if (sp_folder.Exists)
{
FileStream fs = new FileStream(@"c:/Domo.txt", FileMode.Open);
byte[] p_DocBinaryArray = new byte[fs.Length];
fs.Read(p_DocBinaryArray, 0, (int)fs.Length);
sp_folder.Files.Add("Demo.txt", p_DocBinaryArray, true); // overwrite if exists
sp_folder.Update();
result = true;
}
else
{
result = false;
}
}
catch (Exception ex)
{
result = false;
}
finally
{
site.Close();
site.Dispose();
web.Close();
web.Dispose();
}
return result;
}