You can do this using this code:
// Getting a reference to the document library
var sp = new SPSite("http://localhost");
var site = sp.OpenWeb();
var folder = site.GetFolder("Documents");
var files = folder.Files;
// Opening a filestream
var fStream = File.OpenRead("C:MyDocument.docx");
var contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
// Adding any metadata needed
var documentMetadata = new Hashtable {{"Comments", "Hello World"}};
// Adding the file to the SPFileCollection
var currentFile =
files.Add("Documents/MyDocument.docx", contents, documentMetadata, true);
site.Dispose();
sp.Dispose();
link to source
Using client object:
ClientContext context = new ClientContext("http://spdevinwin");
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@"C:\Work\Files\17580_FAST2010_S05_Administration.pptx");
newFile.Url = "17580_FAST2010_S05_Administration 4MB file uploaded via client OM.pptx";
List docs = web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
Console.WriteLine("done");
link to source
Using Java Script:
function createFile(resultpanel) {
var clientContext;
var oWebsite;
var oList;
var fileCreateInfo;
var fileContent;
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
oList = oWebsite.get_lists().getByTitle("Shared Documents");
fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url("my new file.txt");
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
fileContent = "The content of my new file";
for (var i = 0; i < fileContent.length; i++) {
fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
}
this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
clientContext.load(this.newFile);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
resultpanel.innerHTML =
"Go to the " +
"<a href='../Lists/Shared Documents'>document library</a> " +
"to see your new file.";
}
function errorHandler() {
resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
}
}