1

Normally, we can edit a document properties after the document was uploaded.

Is there a way to use something similar to <form> to complete all the required fields at the same time the form is uploaded to a library?

I currently have the form and a way to select a local file to be uploaded but can't figure out how to actually get the file and properties to a library...

<div class="container" style="padding-top: 90px">
<input id="docTitle" class="form-control" type="text" placeholder="Document Name or Title">
<select id="docCategory" class="form-control">
    <option>Guideline</option>
    <option>Instructions</option>
    <option>Plan</option>
    <option>Policy</option>
    <option>Procedure</option>
    <option>Source File</option>
    <option>Standard</option>
    <option>Template</option>
</select>
<div class="form-group">
    <label for="exampleFormControlFile1">File to upload</label>
    <input type="file" class="form-control-file" id="getFile">
</div>
<button id="addFileButton" type="submit" class="btn btn-primary">Submit</button>

EDIT I found below site after much research and was able to upload the file in SPO. I just need to figure out how to apply the properties. How To Upload Document In Document Library Using JSOM In Sharepoint 2013

1

2 Answers 2

0

I suggest you upload files with properties using REST API. The following code for your reference.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        init();
    });
});

function init()
{
    $("#btnUploadFiles").click(function(){
        var files=$("#inputTypeFiles")[0].files;
        uploadFiles(files[0]); // uploading singe file
    });
}

function uploadFiles (uploadFileObj) {
    var fileName = uploadFileObj.name;
    var webUrl = _spPageContextInfo.webAbsoluteUrl;
    var documentLibrary="SampleDocuments";
    var folderName = "Folder1";
    var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
    var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&amp;amp;@target='" + targetUrl + "'";

    uploadFileToFolder(uploadFileObj, url, function (data) {
        var file = data.d;
        var updateObject = {
            __metadata: {
                type: file.ListItemAllFields.__metadata.type
            },
            Column1: 'Test Data',   //meta data column1
            Column2: 'Test Data'    //meta data column2
        };

        url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";

        updateFileMetadata(url, updateObject, file, function (data) {
            alert("File uploaded &amp;amp; meta data updation done successfully");
        }, function (data) {
            alert("File upload done but meta data updating FAILED");
        });
    }, function (data) {
        alert("File uploading and meta data updating FAILED");
    });
}

function getFileBuffer(uploadFile) {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(uploadFile);
    return deferred.promise();
}

function uploadFileToFolder(fileObj, url, success, failure) {
    var apiUrl = url;
    var getFile = getFileBuffer(fileObj);
    getFile.done(function (arrayBuffer) {
        $.ajax({
            url: apiUrl,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            async: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });
}

function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
    $.ajax({
        url: apiUrl,
        type: "POST",
        async: false,
        data: JSON.stringify(updateObject),
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "Content-Type": "application/json;odata=verbose",
            "X-Http-Method": "MERGE",
            "IF-MATCH": file.ListItemAllFields.__metadata.etag,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

Reference:

Upload a file by using the REST API and jQuery

Upload a file into document library using REST API in SharePoint 2013 / Online

0

I got this to work following the link I posted on my original message, and tweaked it a bit to apply the properties:

readFile()

I added all the variables from from the <input> fields, then passed the value to the uploadFile() function

var docTitle = $("#docTitle").val();
var docCategory = $("#docCategory").val();

uploadFile()

Used .get_listItemAllFields() to apply the value from <input> to the library document properties:

    //Update file properties
    var docProp = uploadedDocument.get_listItemAllFields();
    docProp.set_item("Title", docTitle);
    docProp.set_item("Category", docCategory);
    docProp.update();

Complete code

var fileInput; 
var fileName;
var docTitle;
var docCategory;

$(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();
    var docTitle = $("#docTitle").val();
    var docCategory = $("#docCategory").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, docTitle, docCategory);  
    }  
    reader.onerror = function (e) {  
        alert(e.target.error);  
    }  
    reader.readAsArrayBuffer(file);  
}  
var attachmentFiles; 
var siteUrl = '/sites/xxx/forms';

function uploadFile(arrayBuffer, fileName, docTitle, docCategory) {  
    //Get Client Context,Web and List object.  
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Documents');  

    //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);  

    //Update file properties
    var docProp = uploadedDocument.get_listItemAllFields();
    docProp.set_item("Title", docTitle);
    docProp.set_item("Category", docCategory);
    docProp.update();

    //Load client context and execcute the batch 
    clientContext.load(uploadedDocument);
    clientContext.executeQueryAsync(QuerySucceeded, QueryFailed); 
}  

function QuerySucceeded() {
    console.log('File uploaded successfully');
    alert('File uploaded successfully');
}  

function QueryFailed(sender, args) {  
    console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
    alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());  
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.