File Upload Progress Bar Sharepoint Sp Pnp Js Core

@pnp/sp/files¶

1 of the more than challenging tasks on the client side is working with SharePoint files, especially if they are large files. We have added some methods to the library to assist and their use is outlined beneath.

Reading Files¶

Reading files from the client using Residuum is covered in the below examples. The important matter to remember is choosing which format you desire the file in and so you can appropriately process information technology. Y'all tin recollect a file as Blob, Buffer, JSON, or Text. If you have a special requirement you could also write your own parser.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders";  const sp = spfi(...);  const blob: Hulk = await sp.web.getFileByServerRelativePath("/sites/dev/documents/file.avi").getBlob();  const buffer: ArrayBuffer = await sp.web.getFileByServerRelativePath("/sites/dev/documents/file.avi").getBuffer();  const json: any = await sp.spider web.getFileByServerRelativePath("/sites/dev/documents/file.json").getJSON();  const text: string = await sp.web.getFileByServerRelativePath("/sites/dev/documents/file.txt").getText();  // all of these also work from a file object no affair how you access it const text2: string = expect sp.web.getFolderByServerRelativePath("/sites/dev/documents").files.getByUrl("file.txt").getText();                              

getFileByUrl¶

This method supports opening files from sharing links or absolute urls. The file must reside in the site from which you lot are trying to open the file.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files/spider web";  const sp = spfi(...);  const url = "{accented file url OR sharing url}";  // file is an IFile and supports all the file operations const file = sp.web.getFileByUrl(url);  // for example const fileContent = look file.getText();                              

Adding Files¶

Also you can add files using one of two methods, addUsingPath or addChunked. AddChunked is appropriate for larger files, generally larger than 10 MB just this may differ based on your bandwidth/latency and so you tin can suit the code to use the chunked method. The below example shows getting the file object from an input and uploading information technology to SharePoint, choosing the upload method based on file size.

The addUsingPath method, supports the percent or pound characters in file names.

                declare var require: (s: string) => any;  import { ConsoleListener, Logger, LogLevel } from "@pnp/logging";  import { Spider web } from "@pnp/sp/webs"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders"; import { auth } from "./auth"; permit $ = crave("jquery"); // <-- used here for illustration  let siteUrl = "https://mytenant.sharepoint.com/sites/dev";  // comment this out for non-node execution // auth(siteUrl);  Logger.subscribe(new ConsoleListener()); Logger.activeLogLevel = LogLevel.Verbose;  let spider web = Web(siteUrl);   $(() => {     $("#testingdiv").append("<button id='thebuttontodoit'>Practice It</button>");      $("#thebuttontodoit").on('click', async (east) => {          east.preventDefault();          let input = <HTMLInputElement>document.getElementById("thefileinput");         let file = input.files[0];          // you can accommodate this number to control what size files are uploaded in chunks         if (file.size <= 10485760) {              // small upload             look web.getFolderByServerRelativePath("Shared Documents").files.addUsingPath(file.name, file, {Overwrite: true});             Logger.write("done");         } else {              // large upload             wait web.getFolderByServerRelativePath("Shared Documents").files.addChunked("filename%#%.txt", file, data => {                  Logger.log({ data: data, level: LogLevel.Verbose, message: "progress" });              }, true);             Logger.write("done!")         }     }); });                              

Calculation a file using Nodejs Streams¶

If you lot are working in nodejs you can also add a file using a stream. This case makes a re-create of a file using streams.

Batching Not Supported Banner

                // triggers machine-awarding of extensions, in this case to add getStream  import "@pnp/nodejs"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; import "@pnp/sp/files"; import { createReadStream } from 'fs'; import { SPDefault } from "@pnp/nodejs"; import { ThrowErrors } from "@pnp/queryable";  // go a stream of an existing file const stream = createReadStream("c:/temp/file.txt");  // now add the stream as a new file, recollect to set the content-length header const sp = spfi("{tenant url}").using(SPDefault({     baseUrl: 'https://{tenant}.sharepoint.com/sites/dev',     msal: {         config: config,         scopes: [ 'https://{tenant}.sharepoint.com/.default' ]     } })).using(ThrowErrors());  const fr = wait sp.web.lists.getByTitle("Documents").rootFolder.files.addChunked( "new.txt", stream, undefined, true );                              

Setting Associated Item Values¶

You can also update the file backdrop of a newly uploaded file using code similar to the below snippet:

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders";  const sp = spfi(...); const file = expect sp.web.getFolderByServerRelativePath("/sites/dev/Shared%20Documents/examination/").files.addUsingPath("file.name", "content", {Overwrite: truthful}); const detail = look file.file.getItem(); expect item.update({   Title: "A Title",   OtherField: "My Other Value" });                              

Update File Content¶

You can of grade use like methods to update existing files equally shown below. This overwrites the existing content in the file.

Batching Not Supported Banner

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders";  const sp = spfi(...); look sp.spider web.getFileByServerRelativePath("/sites/dev/documents/test.txt").setContent("New cord content for the file.");  wait sp.web.getFileByServerRelativePath("/sites/dev/documents/test.mp4").setContentChunked(file);                              

Check in, Bank check out, and Approve & Deny¶

The library provides helper methods for checking in, checking out, and blessing files. Examples of these methods are shown below.

Check In¶

Bank check in takes two optional arguments, comment and check in type.

                import { spfi } from "@pnp/sp"; import { CheckinType } from "@pnp/sp/files"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  // default options with empty comment and CheckinType.Major wait sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").checkin(); console.log("File checked in!");  // supply a comment (< 1024 chars) and using default cheque in type CheckinType.Major await sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").checkin("A comment"); console.log("File checked in!");  // Supply both comment and check in type await sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").checkin("A comment", CheckinType.Overwrite); console.log("File checked in!");                              

Cheque Out¶

Check out takes no arguments.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").checkout(); console.log("File checked out!");                              

Approve and Deny¶

You can also approve or deny files in libraries that use approval. Approve takes a single required argument of annotate, the comment is optional for deny.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  await sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").corroborate("Approval Comment"); console.log("File approved!");  // deny with no comment expect sp.spider web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").deny(); console.log("File denied!");  // deny with a supplied comment. expect sp.spider web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").deny("Deny comment"); console.log("File denied!");                              

Publish and Unpublish¶

You can both publish and unpublish a file using the library. Both methods take an optional comment statement.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  // publish with no comment await sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").publish(); panel.log("File published!");  // publish with a supplied comment. await sp.spider web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").publish("Publish comment"); console.log("File published!");  // unpublish with no comment look sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").unpublish(); panel.log("File unpublished!");  // unpublish with a supplied annotate. await sp.web.getFileByServerRelativePath("/sites/dev/shared documents/file.txt").unpublish("Unpublish comment"); panel.log("File unpublished!");                              

Avant-garde Upload Options¶

Both the addChunked and setContentChunked methods back up options beyond just supplying the file content.

Batching Not Supported Banner

progress function¶

A method that is chosen each time a clamper is uploaded and provides plenty data to report progress or update a progress bar easily. The method has the signature:

(data: ChunkedFileUploadProgressData) => void

The data interface is:

                export interface ChunkedFileUploadProgressData {     stage: "starting" | "go along" | "finishing";     blockNumber: number;     totalBlocks: number;     chunkSize: number;     currentPointer: number;     fileSize: number; }                              

chunkSize¶

This belongings controls the size of the individual chunks and is defaulted to 10485760 bytes (10 MB). You tin can arrange this based on your bandwidth needs - specially if writing code for mobile uploads or you are seeing frequent timeouts.

getItem¶

This method allows yous to get the item associated with this file. You can optionally specify one or more select fields. The result will be merged with a new Particular case so you will have both the returned property values and chaining ability in a single object.

                import { spFI, SPFx } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders"; import "@pnp/sp/security";  const sp = spfi(...);  const item = look sp.spider web.getFileByServerRelativePath("/sites/dev/Shared Documents/exam.txt").getItem(); panel.log(item);  const item2 = await sp.web.getFileByServerRelativePath("/sites/dev/Shared Documents/examination.txt").getItem("Title", "Modified"); console.log(item2);  // you tin can also concatenation direct off this item case const perms = expect item.getCurrentUserEffectivePermissions(); panel.log(perms);                              

You can also supply a generic typing parameter and the resulting blazon will exist a union type of Item and the generic type parameter. This allows you lot to accept proper intellisense and type checking.

                import { spFI, SPFx } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import "@pnp/sp/folders"; import "@pnp/sp/items"; import "@pnp/sp/security";  const sp = spfi(...);  // also supports typing the objects so your type will be a union type const item = await sp.spider web.getFileByServerRelativePath("/sites/dev/Shared Documents/test.txt").getItem<{ Id: number, Title: string }>("Id", "Title");  // Y'all get intellisense and proper typing of the returned object console.log(`Id: ${detail.Id} -- ${item.Title}`);  // You can likewise chain straight off this item instance const perms = await item.getCurrentUserEffectivePermissions(); console.log(perms);                              

movement¶

It'southward possible to move a file to a new destination within a site collection

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  // destination is a server-relative url of a new file const destinationUrl = `/sites/dev/SiteAssets/new-file.docx`;  await sp.web.getFileByServerRelativePath("/sites/dev/Shared Documents/test.docx").moveByPath(destinationUrl, false, true);                              

copy¶

It's possible to copy a file to a new destination within a site collection

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  // destination is a server-relative url of a new file const destinationUrl = `/sites/dev/SiteAssets/new-file.docx`;  await sp.web.getFileByServerRelativePath("/sites/dev/Shared Documents/test.docx").copyTo(destinationUrl, false);                              

copy by path¶

It'south possible to copy a file to a new destination within the aforementioned or a unlike site collection

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...);  // destination is a server-relative url of a new file const destinationUrl = `/sites/dev2/SiteAssets/new-file.docx`;  look sp.web.getFileByServerRelativePath("/sites/dev/Shared Documents/test.docx").copyByPath(destinationUrl, false, true);                              

getFileById¶

You can go a file past Id from a web.

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files"; import { IFile } from "@pnp/sp/files";  const sp = spfi(...);  const file: IFile = sp.web.getFileById("2b281c7b-ece9-4b76-82f9-f5cf5e152ba0");                              

delete¶

Deletes a file

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...); expect sp.web.getFolderByServerRelativePath("{folder relative path}").files.getByUrl("filename.txt").delete();                              

delete with params¶

Deletes a file with options

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...); await sp.spider web.getFolderByServerRelativePath("{folder relative path}").files.getByUrl("filename.txt").deleteWithParams({     BypassSharedLock: truthful, });                              

exists¶

Checks to meet if a file exists

                import { spfi } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/files";  const sp = spfi(...); const exists = await sp.spider web.getFolderByServerRelativePath("{folder relative path}").files.getByUrl("name.txt").exists();                              

vincentknines1992.blogspot.com

Source: https://pnp.github.io/pnpjs/sp/files/

0 Response to "File Upload Progress Bar Sharepoint Sp Pnp Js Core"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel