SharePoint 上传文件到图片库中代码

上Application Page中的代码

   /// <summary>
/// 得到上传文件后的文件名称
/// </summary>
/// <param name="up">FileUpload ID</param>
/// <param name="s1">上传后在库里的名称</param>
protected bool GetUploadName(FileUpload up, ref string s1)
{
bool res = true;
if (up.HasFile)
{
string sName1 = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddhhmmss"),
System.IO.Path.GetExtension(up.FileName).ToLower());
string result1 = JSharePoint.Core.SPUnits.CommonOperate.UploadFileToImgLib(up.PostedFile.FileName, sName1, ref s1);
if (!result1.Equals("Success"))
{
res = false;
MessageBox.Show(Page, result1);
}
}
return res;

}


类CommonOperate类的代码

        public static string UploadFileToImgLib(string sSourcePath, string sFilename, ref string sFilePath)
{
return UploadFile(sSourcePath,Constant.sImageLibraryName,sFilename,ref sFilePath);
}

/// <summary>
/// 上传文件 到指定的路径中
/// </summary>
/// <param name="sSourcePath">文件的原地址</param>
/// <param name="sDistPath">目标地址</param>
/// <param name="sFilename">上传后的文件名称</param>
/// <param name="strUserName“>用户名</param>
/// <param name="strPassword">密码</param>
/// <param name="strDomain">域名</param>
/// <returns></returns>
public static string UploadFile(string sSourcePath, string sListName, string sFilename, ref string sFilePath)
{
string strResult = "Success";
SecurityContext sc = new SecurityContext(SPContext.Current.Site.ID, SPContext.Current.Web.ID);
try
{
FileStream fileStream = File.OpenRead(sSourcePath);
SPFolderCollection fls = sc.Lists[sListName].RootFolder.SubFolders;
SPFile oFile = fls.Folder.Files.Add(sFilename, fileStream, true);
sFilePath = oFile.ServerRelativeUrl;
oFile.Update();

sc.Dispose();
}
catch (Exception ex)
{
sc.Dispose();
strResult = "Failed! " + ex.Message;
}
return strResult;
}
原文地址:https://www.cnblogs.com/gzh4455/p/2374748.html