Upload Document along with meta data using JSOM
<script language="javascript" type="text/javascript" src="/sites/ProposalRepository/SiteAssets/ProposalRepository/js/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var fileInput;
var fileName;
$(document).ready(function() {
fileInput = $("#getFile");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
});
function registerClick() {
//Register File Upload Click Event
$("#addFileButton").click(readFile);
}
var arrayBuffer;
function readFile() {
var fileVal = $("#getFile").val();
//Get File Input Control and read th file name
var element = document.getElementById("getFile");
var file = element.files[0];
var parts = element.value.split("\\");
fileName = parts[parts.length - 1];
//Read File contents using file reader
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;
function uploadFile(arrayBuffer, fileName) {
//Get Client Context,Web and List object.
var clientContext = new SP.ClientContext();
var oWeb = clientContext.get_web();
var oList = oWeb.get_lists().getByTitle('Name of your Document Library');
//Convert the file contents into base64 data
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);
//Create FileCreationInformation object using the read file data
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(base64);
createInfo.set_overwrite(true); //want to overwrite the file with same name
createInfo.set_url(fileName);
//Add the file to the library
var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
//Load client context and execcute the batch
clientContext.load(uploadedDocument);
clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
}
function QuerySuccess() {
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('ProposalDocuments');
var element = document.getElementById("getFile");
var file = element.files[0];
var parts = element.value.split("\\");
fileName = parts[parts.length - 1];
var fileName = fileName;
var collListItem;
var oListItem;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
"<View Scope='RecursiveAll'><Query>" +
"<Where>" +
"<Eq><FieldRef Name=\"FileLeafRef\"/><Value Type=\"Text\">" + fileName + "</Value></Eq>" +
"</Where>" +
"</Query></View>");
collListItem = list.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(function() {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
console.log(oListItem.get_id());
var docID = oListItem.get_id(); //getting file id from library
}
UpdateListItem('Name of your document library', docID, 'testMetaData');
}, function(sender, args) {
console.log("something went wrong");
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
});
console.log('File Uploaded Successfully.');
// alert("File Uploaded Successfully.");
}
function QueryFailure(sender, args) {
console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
}
function UpdateListItem(listName, itemId, titleVal) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": titleVal
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function(data) {
console.log('Success');
alert('File Uploaded');
window.location = "http://korbsbvm113:2728/sites/ProposalRepository/SitePages/Home.aspx";
},
error: function(data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "Item";
}
</script>
Proposal Document
<div class="Pagebtn">
<input id="addFileButton" type="button" value="Submit" />
<input id="cancelBtn" type="button" value="Close"/>
</div>