Create your document library with the respective folders.
Create a txt file and add the below code (after making necessary changes at the highlighted areas, such as - your library name, folder name respectively) and save it in Site Assets.
- <html> <head> <script language="javascript" type="text/javascript" src="https://industowers.sharepoint.com/sites/LPMS/Style%20Library/LPMS/JS/1.8.1jquery.min.js">
- </script>
-
- <script language="javascript" type="text/javascript">
- var fileInput;
- $(document).ready(function()
- {
- fileInput = $("#getFile");
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
- });
-
- function registerClick()
- {
-
- $("#addFileButton").click(readFile);
- }
- var arrayBuffer;
-
- function readFile()
- {
-
- var element = document.getElementById("getFile");
- var file = element.files[0];
- var parts = element.value.split("\\");
- var fileName = parts[parts.length - 1];
-
- var reader = new FileReader();
- reader.onload = function(e) {
- uploadFile(e.target.result, fileName);
- }
- reader.onerror = function(e)
- {
- alert(e.target.error);
- }
- reader.readAsArrayBuffer(file);
- }
- var attachmentFiles, clientContext, createInfo;
-
- function uploadFile(arrayBuffer, fileName)
- {
-
- clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
-
-
- var oList = oWeb.get_lists().getByTitle('CS100');
- var attachmentFolder = oWeb.getFolderByServerRelativeUrl('/sites/LPMS/CS100/Trial');
-
-
- var bytes = new Uint8Array(arrayBuffer);
- var i, length, out = '';
- for (i = 0, length = bytes.length; i < length; i += 1) {
- out += String.fromCharCode(bytes[i]);
- }
- var base64 = btoa(out);
-
- createInfo = new SP.FileCreationInformation();
- createInfo.set_content(base64);
- createInfo.set_url(fileName);
-
-
- attachmentFiles = attachmentFolder.get_files().add(createInfo);
-
-
- clientContext.load(oList);
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
-
- function QuerySuccess()
- {
- console.log("Attachment added successfuly ");
- }
-
- function QueryFailure(sender, args)
- {
- console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
- }
- </script>
-
- </head>
- <body> <input id="getFile" type="file"/><br /> <input id="addFileButton" type="button" value="Upload" /> </body> <html>
Take the path of the file and save it.
Create a site page and add a CEWP to pull that file using the path saved earlier. Click "Apply" and save the site page.
Start uploading the attachments.
You can see the uploading of attachments happening.
Note
The above approach is successful on both, SharePoint Online and SharePoint On premise environments; as this is simple JavaScript client-side coding.
Keep changing the folder name and library name for your respective folder-wise documents whenever required.