C# 使用自定义字段类型的SharePoint自定义上载页面
是否可以在SharePoint中创建自定义上载页面,将文件上载控件与自定义字段类型组合在一起,以便用户可以选择要从硬盘上载的文件,输入文件标题,或者添加注释,指定内容类型并在多个自定义字段中输入其他数据,创建新的SPListItem,上载文件并与新的SPListItem关联,最后将输入自定义字段的所有值成功保存到新创建的SPListItem 注意:我希望仅使用SharePoint自定义字段类型执行此任务,而不使用带有一组用户控件的自定义ASPX页面 使用自定义字段类型时存在的根本问题是SharePoint文档库中的文件上载事件是异步事件。您可以覆盖SPListItemEventReceiver中可用的ItemAdding方法的默认行为,该方法可用于在上载文件时访问某些信息“”,同样,您也可以从名为的ItemAdded方法访问有关新创建的SPListItem的信息“添加项目后”-但由于此方法发生在单独的线程中,并且异步执行,不知道与自定义字段或其各自值相关的任何内容,因此用户在这些字段中输入的任何数据都不会成功保存 当用户希望通过使用EditFormTemplate编辑自定义字段中的值来更新有关文档的信息时,每个字段的SPListItem属性都会在初始化过程中设置。这一切都可以正常工作,因为在这种情况下,ListItem已经存在!问题是当用户希望上载文档以进行更新时第一次,ListItem显然还不存在,因此每个字段都使用设置为“null”的SPListItem属性进行初始化“并且将永远保持为空,因为在上传文件后,似乎没有任何方法可以通过引用新创建的ListItem来追溯更新每个字段的ListItem属性 正是出于这个原因,也正是出于这个原因,微软坚持要求用户在一个屏幕上上传他们的文件,然后在成功上传文件后将其重定向到编辑表单。通过拆分这两个页面,Microsoft强制用户上载该文件,并在保存有关该文件的任何其他信息之前创建ListItem。上载文件并创建ListItem后,将每个自定义字段的值保存回ListItem不会出现问题,因为ListItem已经存在 注意:BaseFieldControl继承自FieldMetadata,后者继承自FormComponent。FormComponent有一个名为Item的属性,该属性对应于该字段所属的基础SPListItem。BaseFieldControl有一个名为ListItemFieldValue的属性,该属性存储保存回ListItem的字段的实际值,它还有一个名为UpdateFieldValueInItem()的可重写方法,可用于执行附加逻辑(如验证)将数据分配给ItemFieldValue属性之前 当更新现有的SPListItem时,以下代码有效,自定义字段值将被保存,因为SPListItem已经存在C# 使用自定义字段类型的SharePoint自定义上载页面,c#,sharepoint,file-upload,custom-fields,event-receiver,C#,Sharepoint,File Upload,Custom Fields,Event Receiver,是否可以在SharePoint中创建自定义上载页面,将文件上载控件与自定义字段类型组合在一起,以便用户可以选择要从硬盘上载的文件,输入文件标题,或者添加注释,指定内容类型并在多个自定义字段中输入其他数据,创建新的SPListItem,上载文件并与新的SPListItem关联,最后将输入自定义字段的所有值成功保存到新创建的SPListItem 注意:我希望仅使用SharePoint自定义字段类型执行此任务,而不使用带有一组用户控件的自定义ASPX页面 使用自定义字段类型时存在的根本问题是Share
var item = MyDocLib.Items[0] as SPListItem;
item["MyCustomFieldName"] = "some value";
item.Update();
在SPListItemEventReceiver中,在初始文件上载期间,在创建ListItem和单个自定义字段值“尝试保存”之后,ItemUpdate/ItemUpdate方法将包含SPItemEventProperties.ListItem的空引用,因为如前所述,ItemAdded方法是异步启动的,新创建的ListItem在ItemUpdate/ItemUpdate方法中不可用。要上载文件并将其与列表项链接,可以使用字段类型。
注意:它是商业附加组件。可以,因此,创建一个自定义上载表单,将文件上载输入控件和库中的自定义字段与一个或多个OOTB或自定义SPListFieldIterators组合在一起,这不是一项容易的任务,这可能就是为什么Microsoft决定将该过程分为两个不同且完全不相关的操作 尽管如此,允许这种功能还是有其固有的价值,因为它使用户能够在单个原子操作中同时上载文件和持久化元数据,这样您的库中就永远不会存在一个没有任何标识信息的文档 那么它花了多少钱?有几件事 第一个是创建一个实用程序类,我称之为“FileUploader”,这就是它的外观
public class FileUploader
{
#region Fields
private readonly SPList list;
private readonly FileUpload fileUpload;
private string contentTypeId;
private string folder;
private SPContext itemContext;
private int itemId;
#endregion
#region Properties
public bool IsUploaded
{
get
{
return this.itemId > 0;
}
}
public SPContext ItemContext
{
get
{
return this.itemContext;
}
}
public int ItemId
{
get
{
return this.itemId;
}
}
public string Folder
{
get
{
return this.folder;
}
set
{
this.folder = value;
}
}
public string ContentTypeId
{
get
{
return this.contentTypeId;
}
set
{
this.contentTypeId = value;
}
}
#endregion
public FileUploader(SPList list, FileUpload fileUpload, string contentTypeId)
{
this.list = list;
this.fileUpload = fileUpload;
this.contentTypeId = contentTypeId;
}
public FileUploader(SPList list, FileUpload fileUpload, string contentTypeId, string folder)
{
this.list = list;
this.fileUpload = fileUpload;
this.contentTypeId = contentTypeId;
this.folder = folder;
}
public event EventHandler FileUploading;
public event EventHandler FileUploaded;
public event EventHandler ItemSaving;
public event EventHandler ItemSaved;
public void ResetItemContext()
{
//This part here is VERY, VERY important!!!
//This is where you "trick/hack" the SPContext by setting it's mode to "edit" instead
//of "new" which gives you the ability to essentially initialize the
//SPContext.Current.ListItem and set it's ItemId value. This of course could not have
//been accomplished before because in "new" mode there is no ListItem.
//Once you've done all that then you can set the FileUpload.itemContext
//equal to the SPContext.Current.ItemContext.
if (this.IsUploaded)
{
SPContext.Current.FormContext.SetFormMode(SPControlMode.Edit, true);
SPContext.Current.ResetItem();
SPContext.Current.ItemId = itemId;
this.itemContext = SPContext.Current;
}
}
public bool TryRedirect()
{
try
{
if (this.itemContext != null && this.itemContext.Item != null)
{
return SPUtility.Redirect(this.ItemContext.RootFolderUrl, SPRedirectFlags.UseSource, HttpContext.Current);
}
}
catch (Exception ex)
{
// do something
throw ex;
}
finally
{
}
return false;
}
public bool TrySaveItem(bool uploadMode, string comments)
{
bool saved = false;
try
{
if (this.IsUploaded)
{
//The SaveButton has a static method called "SaveItem()" which you can use
//to kick the whole save process into high gear. Just right-click the method
//in Visuak Studio and select "Go to Definition" in the context menu to see
//all of the juicy details.
saved = SaveButton.SaveItem(this.ItemContext, uploadMode, comments);
if (saved)
{
this.OnItemSaved();
}
}
}
catch (Exception ex)
{
// do something
throw ex;
}
finally
{
}
return saved;
}
public bool TrySaveFile()
{
if (this.fileUpload.HasFile)
{
using (Stream uploadStream = this.fileUpload.FileContent)
{
this.OnFileUploading();
var originalFileName = this.fileUpload.FileName;
SPFile file = UploadFile(originalFileName, uploadStream);
var extension = Path.GetExtension(this.fileUpload.FileName);
this.itemId = file.Item.ID;
using (new EventFiringScope())
{
file.Item[SPBuiltInFieldId.ContentTypeId] = this.ContentTypeId;
file.Item.SystemUpdate(false);
//This code is used to guarantee that the file has a unique name.
var newFileName = String.Format("File{0}{1}", this.itemId, extension);
Folder = GetTargetFolder(file.Item);
if (!String.IsNullOrEmpty(Folder))
{
file.MoveTo(String.Format("{0}/{1}", Folder, newFileName));
}
file.Item.SystemUpdate(false);
}
this.ResetItemContext();
this.itemContext = SPContext.GetContext(HttpContext.Current, this.itemId, list.ID, list.ParentWeb);
this.OnFileUploaded();
return true;
}
}
return false;
}
public bool TryDeleteItem()
{
if (this.itemContext != null && this.itemContext.Item != null)
{
this.ItemContext.Item.Delete();
return true;
}
return false;
}
private SPFile UploadFile(string fileName, Stream uploadStream)
{
SPList list = SPContext.Current.List;
if (list == null)
{
throw new InvalidOperationException("The list or root folder is not specified.");
}
SPWeb web = SPContext.Current.Web;
SPFile file = list.RootFolder.Files.Add(fileName, uploadStream, true);
return file;
}
private string GetTargetFolder(SPListItem item)
{
var web = item.Web;
var rootFolder = item.ParentList.RootFolder.ServerRelativeUrl;
var subFolder = GetSubFolderBasedOnContentType(item[SPBuiltInFieldId.ContentTypeId]);
var folderPath = String.Format(@"{0}/{1}", rootFolder, subFolder);
var fileFolder = web.GetFolder(folderPath);
if (fileFolder.Exists) return folderPath;
return Folder;
}
private void OnFileUploading()
{
EventHandler handler = this.FileUploading;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
private void OnFileUploaded()
{
EventHandler handler = this.FileUploaded;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
private void OnItemSaving()
{
EventHandler handler = this.ItemSaving;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
private void OnItemSaved()
{
EventHandler handler = this.ItemSaved;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
然后我在我的“CustomUpload”类中使用了它,该类是我的ASPX页面的代码隐藏
public partial class CustomUpload : LayoutsPageBase
{
#region Fields
private FileUploader uploader;
#endregion
#region Properties
public SPListItem CurrentItem { get; set; }
public SPContentType ContentType { get; set; }
public int DocumentID { get; set; }
private SPList List;
#endregion
public CustomUpload()
{
SPContext.Current.FormContext.SetFormMode(SPControlMode.New, true);
}
protected override void OnInit(EventArgs e)
{
if (IsPostBack)
{
// Get content type id from query string.
string contentTypeId = this.Request.QueryString["ContentTypeId"];
string folder = this.Request.QueryString["RootFolder"];
//ALL THE MAGIC HAPPENS HERE!!!
this.uploader = new FileUploader(SPContext.Current.List, this.NewFileUpload, contentTypeId, folder);
//These event handlers are CRITIAL! They are what enables you to perform the file
//upload, get the newly created ListItem, DocumentID and MOST IMPORTANTLY...
//the newly initialized ItemContext!!!
this.uploader.FileUploading += this.OnFileUploading;
this.uploader.FileUploaded += this.OnFileUploaded;
this.uploader.ItemSaving += this.OnItemSaving;
this.uploader.ItemSaved += this.OnItemSaved;
this.uploader.TrySaveFile();
}
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
//put in whatever custom code you want...
}
protected void OnSaveClicked(object sender, EventArgs e)
{
this.Validate();
var comments = Comments.Text;
if (this.IsValid && this.uploader.TrySaveItem(true, comments))
{
this.uploader.TryRedirect();
}
else
{
this.uploader.TryDeleteItem();
}
}
private void OnFileUploading(object sender, EventArgs e)
{
}
private void OnFileUploaded(object sender, EventArgs e)
{
//This is the next VERY CRITICAL piece of code!!!
//You need to retrieve a reference to the ItemContext that is created in the FileUploader
//class and then set your SPListFieldIterator's ItemContext equal to it.
this.MyListFieldIterator.ItemContext = this.uploader.ItemContext;
ContentType = this.uploader.ItemContext.ListItem.ContentType;
this.uploader.ItemContext.FormContext.SetFormMode(SPControlMode.Edit, true);
}
private void OnItemSaving(object sender, EventArgs e)
{
}
private void OnItemSaved(object sender, EventArgs e)
{
using (new EventFiringScope())
{
//This is where you could technically set any values for the ListItem that are
//not tied into any of your custom fields.
this.uploader.ItemContext.ListItem.SystemUpdate(false);
}
}
}
好的……那么这些代码的要点是什么
如果你对我提供的评论不感兴趣,我会给你一个简短的总结
基本上,代码所做的是使用FileUploaderhelper类执行整个文件上载过程,并使用一系列EventHandler,这些事件处理程序附加到各种SPItem和SPFile相关事件(即保存/保存和上载/上载)允许新创建的SPListItem和ItemContext对象以及SPListItem.Id值与CustomUpload类中使用的SPContext.Current.ItemContext同步。一旦你有了一个有效的和新刷新的ItemContext,你就可以“鬼鬼祟祟地”设置我们正在使用的现有ItemContext