Forum Discussion
harrychen1
Jan 08, 2019Copper Contributor
PnP JS to attach files to list item from SharePoint framework issue - cannot pass file content
I try to use PnP JS to attach files to list item from SharePoint framework and have issue to pass file content.
0. I'm not using any javascript framework to simplify the demo
1. Here is the HTML in the render()
...
<input id="inputfile" type="file" multiple /> // Files to attach
<input id="EmployeeId" placeholder="EmployeeId" /> // Item ID for file attachment
...
<button id="AttacheFiles" type="submit" >Attache Files</button>
2. Added event
private AddEventListeners() : void{
document.getElementById('AttacheFiles').addEventListener('click',()=>this.AttachFiles());
}
3. Handle event code.
private AttachFiles()
{
var files = document.getElementById('inputfile');
var attachments: AttachmentFileInfo[] = [];
var fileCount = (<HTMLInputElement>document.getElementById('inputfile')).files.length;
for (var i = 0; i < fileCount; i++) {
let firstInput = (<HTMLInputElement>document.getElementById('inputfile')).files[i];
var reader = new FileReader();
var rawData;
reader.onload = function(e) {
rawData = reader.result; //This should be updated after reader.readAsBinaryString(firstInput);
};
reader.readAsBinaryString(firstInput);
rawData = reader.result;
alert("Total File name " + firstInput.name);
alert("File content " + rawData ); // This is always empty!!!
attachments.push({
name: firstInput.name,
content: rawData // rawData is empty. If I hard coded content like "My test". The code is working
// Question #1 : How to set the content???
});
}
sp.web.lists.getByTitle("EmployeeList1").items.getById(document.getElementById('EmployeeId')["value"]).attachmentFiles.addMultiple(attachments).then(v => {
//Question #2: How to display exceptions?
alert(v); // Never invoked.
});
alert("Record with Employee ID : "+ document.getElementById('EmployeeId')["value"] + " File Attached !");
}
I've included the two questions inline.
Question #1 : How to set the content?
Question #2: How to display exceptions for PnP JS?
Thanks in advance.
1 Reply
- harrychen1Copper Contributor
Issue resolved after I changed the code to process files in input file element change event. All thse code will be outside default class.
The code looks like below.
var fileInfos = [];$(document).ready(function() {$('#inputfile').on('change', function() {processFile();});});// Try this later https://www.javascripture.com/FileReaderfunction processFile() {var input = (<HTMLInputElement>document.getElementById('inputfile'));var fileCount = input.files.length;console.log(fileCount);for (var i = 0; i < fileCount; i++) {var fileName = input.files[i].name;console.log(fileName);var file = input.files[i];var reader = new FileReader();reader.onload = (function(file) {return function(e) {console.log(file.name);fileInfos.push({"name": file.name,//"content": reader.result"content": e.target.result});console.log(fileInfos);};}) (file);reader.readAsArrayBuffer(file);}