Uploading files to a SharePoint library can be done using the Add method on the Files property of a SPWeb like this:
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.
SPContext.Current.Web.Files. "/" + fileUpload.FileName, contents); |
_________________________________________________________________
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( |
Controls.Add( |
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. |
byte [] contents = new byte [fStream.Length]; |
fStream.Read(contents, 0, ( int )fStream.Length); |
fStream.Close(); |
SPSecurity. false ; |
try |
{ |
SPContext.Current. "/" + 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( |
{ |
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[ |
} |
catch (ArgumentException) |
{ |
throw new Exception( "List not found!" ); |
} |
} |
}
No comments:
Post a Comment