Wednesday, July 11, 2012

Upload Document in Document Library

Uploading files to a SharePoint library can be done using the Add method on the Files property of a SPWeb like this:
SPContext.Current.Web.Files.Add(documentLibrary.RootFolder.Url + "/" + fileUpload.FileName, contents);
In the example that follows we will build a webpart that uploads a file provided by the user to a SharePoint library. Please note that the SPList was not necessary, it is only used to validate that the document library exists.

_________________________________________________________________
public class UploadWP : WebPart
{
private FileUpload fileUpload = new FileUpload();
private Button btnUpload = new Button();
private string documentLibrary;
[WebBrowsable, Personalizable]
public string DocumentLibrary
{
get
{
return documentLibrary;
}
set
{
documentLibrary = value;
}
}
protected override void CreateChildControls()
{
Controls.Add(fileUpload);
Controls.Add(btnUpload);
btnUpload.Text = "Upload";
btnUpload.Click += new EventHandler(OnUploadClick);
}
void OnUploadClick(object sender, EventArgs e)
{
SPList documentLibrary;
try
{
documentLibrary = ValidateList();
}
catch (Exception ex)
{
Controls.Add(new LiteralControl(ex.Message));
return;
}
Stream fStream = fileUpload.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
SPSecurity.CatchAccessDeniedException = false;
try
{
SPContext.Current.Web.Files.Add(documentLibrary.RootFolder.Url + "/" + fileUpload.FileName, contents);
}
catch (UnauthorizedAccessException)
{
Controls.Add(new LiteralControl("You are not authorized to upload files to the document library"));
}
}
private SPList ValidateList()
{
if (string.IsNullOrEmpty(DocumentLibrary))
{
throw new Exception("Please fill the Document Library property!");
}
if (!fileUpload.HasFile)
{
throw new Exception("Please select a file to upload.");
}
try
{
return SPContext.Current.Web.Lists[DocumentLibrary];
}
catch (ArgumentException)
{
throw new Exception("List not found!");
}
}
}

No comments:

Post a Comment