PNP-JS Create File from File Lib template - sharepoint

I need to create/add a new File from Files Lib, then i need to set the name of the file with an unique ID and update other fieds. I can update the fields without any problems, but i couldn't find a way to create the file.
How can i possibly achieve the New => Create from template like in the image below
I've tried many ways but nothing fullfill my request.
1
this.web.lists.getByTitle('myFilesLib').items.add() => i get an error about the need to use SPFileCollection.Add()
2
this.web.getFolderByServerRelativeUrl(url).files.addTemplateFile => there is nothing for custom template
3
this.web.getFolderByServerRelativeUrl(url).files.add => i need to provide a file.

For JSOM, you can try this:
newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
For CSOM:
var creationInformation = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem listItem = list.AddItem(creationInformation);
listItem.FieldValues["Foo"] = "Bar";
listItem.Update();
clientContext.ExecuteQuery();
Some wiki for this way: https://social.technet.microsoft.com/wiki/contents/articles/37575.sharepoint-online-working-with-files-inside-document-library-using-jsom.aspx
this.web.getFolderByServerRelativeUrl(url).files.addTemplateFile is used to add page, so it is not suitable for your scenario.
http://www.ktskumar.com/2016/08/pnp-js-core-create-new-page-sharepoint-library/
The PnP JS method requires a File DOM or BLOB object for uploading a file to the SharePoint. Based on the those, we will try two options to upload a file to the SharePoint Library or folder in a library:BLOB/FileAPI
http://www.ktskumar.com/2016/09/pnp-js-core-upload-file-sharepoint/
More reference for you from Microsoft:
https://msdn.microsoft.com/en-us/library/office/dn450841.aspx

This is a sample code to use when you want to upload an existing ContentType to your content library on SharePoint.
const templateUrl = '/sites/App/Template/Forms/Template/test.docx'
const name = 'test.docx'
const depositUrl = '/sites/App/Template'
const web = new Web('http://localhost:8080/sites/App'); // Proxy URL for Dev
web.getFileByServerRelativeUrl(templateUrl)
.getBuffer()
.then((templateData: ArrayBuffer) => {
web.getFolderByServerRelativeUrl(depositUrl).files.add(name, templateData));
});
There is an issue if you use SP-Rest-Proxy at the moment (file is corrupted on SharePoint) but it should be fix soon.
If you Deploy your app on SharePoint, it work as expected.
Related links:
https://github.com/pnp/pnpjs/issues/196#issuecomment-410908170
https://github.com/koltyakov/sp-rest-proxy/issues/61

Related

SPO Modern: How to inject and execute webpart programmatically, using js?

I have only the URL of webpart (example 'https://sitename.com/sites/site-colection/ClientSideAssets/hereisguid/webpartname.js') and I need to inject and run it programmatically via js, is it possible?
It's not officially supported but You can use global variable (available on every modern page) _spComponentLoader. The problem is - it requires You to provide WebPartContext which You cannot simply get outside of SPFx.
If You want to do it in SPFx here is a sample code:
webPartId = hereisguid from Your url
let component = await _spComponentLoader.loadComponentById(webPartId);
let manifest = _spComponentLoader.tryGetManifestById(webPartId);
let wpInstance = new component.default();
context.manifest = manifest;
//#ts-ignore
context._domElement = document.getElementById("<id-of-element-you-want-wp-to-render-in>")
await wpInstance._internalInitialize(context, {}, 1);
wpInstance._properties = webPart.properties;
await wpInstance.onInit();
wpInstance.render();
wpInstance._renderedOnce = true;
Again - I don't think it's supported so try it on Your own risk.
Note this web part must be available at the site You are going to execute this script.

How to download documents from liferay from outside application ..using liferay jsonws or any other way

Hi i am using liferay/api/secure/jsonws services to upload documents, getting documents, from a outside application , in the same way i want to download the documents also, i checked my liferay jsonws , there is no method or service which i can use for download , or i don't know about it , please suggest me a way to download documents from outside application , by using jsonws or any other way is also fine.
Edit after i got to know how to download document.
Hi I tried to download liferay document from outside application by using getURl, but every time for all document i am getting liferay login page content
i have already tried get-file-as-stream json-rpc call but that also giving me null response
the code which i have used is:
final HttpHost targetHost = new HttpHost(hostname.trim());
System.out.println(targetHost.getHostName());
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
System.out.println(creds);
final AuthScope authscope = new AuthScope(targetHost);
httpclient.getCredentialsProvider().setCredentials(authscope, creds);
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
final HttpGet httpget = new HttpGet(hostname+"/documents/" + groupId + "/" + folderId + "/" + filename);
final HttpResponse response = httpclient.execute( httpget, localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
}
}
return null;
} finally {
httpclient.getConnectionManager().shutdown();
}
}
i am adding basic auth header will correct username and password, don't know how this login page is coming, is there any permission which i need to change or any configurations issue, please help in this.
You could use the Liferay WebDav Services to download files from your document-library. The paths to download can be inspected inside of the control-panel when clicking on a file entry (WebDAV URL toogle link). The paths usually look like: /webdav/{site-name}/document_library/{folder-name}/{file-name}
Otherwise, you could mimic the request URLs Liferay creates inside the documents-media portlet to download the file entry.
But you should take care about authentication, when your files (and folders) are not visible to guests.

Windows 10 App - File downloading

I am working with Windows 10 universal app and i want to download a file in that. The file link to Sharepoint server. I have passed token in headr to a web service and then service returned byte array to my WinJS.
Now i want to save the file, how can i do this? I tried several code samples but not working.
var folder = Windows.Storage.ApplicationData.current.localFolder;
folder.createFileAsync("document.docx", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, result.response);
}).then(function () {
//saved
});
I am using above code and it is creating new file but no content is placed there. Please suggest what to do.
You never open the file for WriteAccess. I have included code from my working app. First do this command
StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);
then do this:
// Get the file.
var ageFile = await local.OpenStreamForWriteAsync("Age.txt",CreationCollisionOption.OpenIfExists);
// Read the data.
using (StreamWriter streamWriter = new StreamWriter(ageFile))
{
streamWriter.WriteLine(cmbAgeGroup.SelectedIndex + ";" + DateTime.Now);
streamWriter.Flush();
}
ageFile.Dispose();

Upload a file to a document library in SharePoint 2010 programmatically in client-server application

I am using below code to upload the file in SharePoint 2010 Library
String fileToUpload = #"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
This worked well through my machine. But when I deploy it on server and used the below snippet to upload file in library from my machine, it gives error. It is not getting the file location (C:\YourFile.txt) from local(client) machine.
When you run on the server your code runs under a different account (apppool identity) which does not have the permission to read C drive.
I dont know why would you want to read and upload a file from the same server, looks like you are simply testing Sharepoint Object Model then it is ok
If you are expecting some other app or service to keep an updated file for Sharepoint , it should be moved to the web directory i.e \wwwroot\wss\VirtualDirectories\80 and then use your code to read and update your doc lib (myLibrary) as you are doing.
Are you running this in a console app or "in SharePoint"?
Could it be that the account running the code doesnt have read permissions in C:\?

Windows store app not working

I'm creating a windows store app to read write files.
I gave permissions for document library but still getting this error
App manifest declares document library access capability without specifying at least one file type association
The code snippet of my code:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
String temp = Month.SelectedValue.ToString() + "/" + Day.SelectedValue.ToString() + "/" + Year.SelectedValue.ToString(); //((ComboBoxItem)Month.SelectedItem).Content.ToString();
DateTime date = Convert.ToDateTime(temp);
Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt");
var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(temp, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
}
Any other better approach is also acceptable.
1.I don't have access to Skydrive. 2.Also don't want to use filepicker
You need to specify file type association also.
From: http://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx
Documents Library:
Note You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.
you can find it in the app manifest, when you check documents library in capabilites, you have to fill in atleast one file type association under Declarations tab.
Found exactly what i was looking for. File type associations was to be added in the app.manifest
For those who facing the same problem check this link

Resources