Add file to SharePoint list item column using JavaScript
-
08-02-2021 - |
Question
I created a custom form using PowerApps. In this form one can also add attachments. The attachment column also shows up when I go to the list, but when I go to the list settings, there's no "Anlagen" column.
What I want to achieve is that a user should be able to add files to that list item via JavaScript. I used this in JavaScript, but it says that it can't find the "Anlagen" column. I can't create that column because the type "attachments" does not exist:
onUploadFile() {
var siteUrl = 'https://thesite.sharepoint.com/sites/Playercard/';
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Player');
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
this.oListItem = oList.getItemById(52);
const formData = new FormData();
formData.append("file", this.selectedFile); // appending file
oListItem.set_item('Anlagen', formData);
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
},
onQuerySucceeded: function(){
console.log("Succeeded!")
},
onQueryFailed: function(sender, args){
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
},
How can I add attachments to this using JavaScript or what am I doing wrong?
Solution
We can't create a custom attachment type column in SharePoint, it is the default behavior, we have to attach the attachment to the existing out of the box attachment column.
You can use the below javascript code to attach the attachment :
<html>
<head>
<script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.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()
{
//Register File Upload Click Event
$("#addFileButton").click(readFile);
}
var arrayBuffer;
function readFile()
{
//Get File Input Control and read th file name
var element = document.getElementById("getFile");
var file = element.files[0];
var parts = element.value.split("\\");
var 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, clientContext, createInfo;
function uploadFile(arrayBuffer, fileName)
{
//Get Client Context and Web object.
clientContext = new SP.ClientContext();
var oWeb = clientContext.get_web();
//Get list and Attachment folder where the attachment of a particular list item is stored.
var oList = oWeb.get_lists().getByTitle('NewList');
var attachmentFolder = oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments/1');
//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
createInfo = new SP.FileCreationInformation();
createInfo.set_content(base64);
createInfo.set_url(fileName);
//Add the file to the list item
attachmentFiles = attachmentFolder.get_files().add(createInfo);
//Load client context and execute the batch
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>
Reference URL :
Upload File To List Item In Office 365 As An Attachment Using JavaScript Object Model
As an alternate using the REST API, we can attach the attachment to the SharePoint list:
$(document).ready(function() {
var ID = 1;
var listname = "UploadTEST";
$("#my-attachments").change(function() {
var file = $(this)[0].files[0];
var getFileBuffer = function(file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
};
getFileBuffer(file).then(function(buffer) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",
method: 'POST',
data: buffer,
processData: false,
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
"content-length": buffer.byteLength
}
});
});
});
});
For details you may refer to the below article: