上传文件到Sharepoint上的文件夹或子文件夹

本文关键字:文件夹 Sharepoint 文件 | 更新日期: 2023-09-27 18:01:49

我试图创建一个方法来上传文件流到sharepoint到目前为止,我有这个

        public static void SPUploadFileStream(string username, string filePath, Stream fileData)
    {
        //string siteUrl = Configuration.SPSiteURL;
        string siteUrl = SPContext.Current.Web.Url;
        SPUser currentUser = SPUtils.GetCurrentUser(username);
        if (currentUser == null)
        {
            throw new SPGappUnknownUserException(username);
        }
        using (SPSite site = new SPSite(siteUrl, currentUser.UserToken))
        {
            using (SPWeb web = site.OpenWeb())
            {
                bool allowWebUnsafeUpdt = web.AllowUnsafeUpdates;
                if (!allowWebUnsafeUpdt)
                    web.AllowUnsafeUpdates = true;
                try
                {
                    SPCreateFolder(Path.GetDirectoryName(filePath), username);
                    SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
                }
                catch (Exception ex)
                {
                    LoggingService.LogError(ex);
                    //site.AllowUnsafeUpdates = allowSiteUnsefaUpdt;
                    web.AllowUnsafeUpdates = allowWebUnsafeUpdt;
                    throw new ApplicationException("ERROR "+ ex.ToString());
                }
            }
        }
    }

,但它工作正常,如果我有一个路径像"FOLDER/file.jpg",但它不当我有子文件夹"FOLDER/SUB/file.jpg"谁能给我点建议?

上传文件到Sharepoint上的文件夹或子文件夹

我的猜测是问题在于您的SPCreateFolder方法。它应该递归地创建文件夹。当您尝试使用

添加新文件时
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace

服务器相对路径必须存在。尝试以下方法创建文件夹

private static void SPCreateFolder(SPWeb web, string filepath)
{
    // since you pass this as Path.GetDictionary it's no longer split by '/'
    var foldersTree = filepath.Split('''');
    foldersTree.Aggregate(web.RootFolder, GetOrCreateSPFolder);
}
private static SPFolder GetOrCreateSPFolder(SPFolder sourceFolder, string folderName)
{
    SPFolder destination;
    try
    {
        // return the existing SPFolder destination if already exists
        destination = sourceFolder.SubFolders[folderName];
    }
    catch
    {
        // Create the folder if it can't be found
        destination = sourceFolder.SubFolders.Add(folderName);
    }
    return destination;
}

然后你可以用

执行这个
...
    SPCreateFolder(web, Path.GetDirectoryName(filePath));
    SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
...

如果有帮助请告诉我