public void UploadFile()
{
if (fileUpload.HasFile)
{
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.Split('.')[0];
fileName = fileName + "_" + DateTime.Now.ToString("MMddyyyyHHmm") + ".pdf";
}
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost())
{
try
{
FileCreationInformation newFile = new FileCreationInformation();
byte[] FileContent = fileUpload.FileBytes;
newFile.ContentStream = new MemoryStream(FileContent);
newFile.Url = Path.GetFileName(fileName);
List list = clientContext.Web.Lists.GetByTitle(Constant.BIM_Comm_Docs);
Folder Clientfolder = list.RootFolder;
var uploadFile = Clientfolder.Files.Add(newFile);
clientContext.Load(Clientfolder);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
}
catch (Exception ex)
{
ErrorLog(clientContext, ex.Message, ex.Source, "UploadFile", "Default.aspx");
}
}
}
}
============================================================
// Get pdf file byte content
public void GetLatestFileFromLibrary()
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
try
{
List list = clientContext.Web.Lists.GetByTitle(Constant.BIM_Comm_Docs);
var q = new CamlQuery() { ViewXml = "<View><Query><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query><RowLimit>1</RowLimit> </View>" };
var items = list.GetItems(q);
clientContext.Load(items);
clientContext.ExecuteQuery();
if (items != null && items.Count > 0)
{
Microsoft.SharePoint.Client.ListItem item = items[0];
var filePath = Convert.ToString(item["FileRef"]);
Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(filePath);
if (file != null)
{
var stream = file.OpenBinaryStream();
clientContext.Load(file);
clientContext.ExecuteQuery();
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
if (stream != null)
{
stream.Value.CopyTo(mStream);
byte[] bytes = mStream.ToArray();
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
hdnByteArray.Value = base64String;
}
}
}
}
}
catch (Exception ex)
{
ErrorLog(clientContext, ex.Message, ex.Source, "GetLatestFileFromLibrary", "Default.aspx");
}
}
}
No comments:
Post a Comment