<script type="text/javascript">
function uploadFile() {
var fileInput = document.getElementById("fileInput");
var file = fileInput.files[0];
if (file) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle("Your List Name");
var folder = list.get_rootFolder();
context.load(folder);
// Read the file data
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
// Create a new file creation information object
var fileInfo = new SP.FileCreationInformation();
fileInfo.set_url(file.name);
fileInfo.set_content(new SP.Base64EncodedByteArray());
// Convert the file data to byte array
var byteArray = new Uint8Array(evt.target.result);
for (var i = 0; i < byteArray.byteLength; i++) {
fileInfo.get_content().append(byteArray[i]);
}
// Upload the file to the list
var uploadedFile = folder.get_files().add(fileInfo);
context.load(uploadedFile);
// Execute the upload request
context.executeQueryAsync(
function () {
// File uploaded successfully
console.log("File uploaded successfully");
},
function (sender, args) {
// Error occurred while uploading file
console.log("Error uploading file: " + args.get_message());
}
);
}
};
// Read the file as an ArrayBuffer
reader.readAsArrayBuffer(file);
}
}
</script>
<!-- HTML Markup -->
<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
Comments
Post a Comment