2

I'm developing an HTML page, which shows files from a certain dictionary from ths Sharepoint. In this page I want to add an option to create a new file to the dictionary. I didn't find a way to do that without ths SP objects, which I don't want to use.

So, is there a way create a new file in SharePoint with javascript?

Edit thanks for all of your answers, but my scenario requires me to create a new empty file, not to upload one.

Please help (:

1

With "simple" REST API, you can do almost anything you can do with the JavaScript API. The REST API does not require any SP.js or other SharePoint JavaScript file. You can consume this REST API from any language, and also from JavaScript (with jQuery to simplify the Ajax calls).

To upload a file, you'll find your happiness here: https://msdn.microsoft.com/en-us/library/office/dn769086.aspx#UploadFile. The _spPageContextInfo call you'll find in the cde is the only "SP.js" artefact, but it is used only to get the target site URL: you can easily replace it with a hard-coded URL, a user-parameter or build it from the current address.

And here, the REST call example to delete a file: https://msdn.microsoft.com/en-us/library/office/dn292553.aspx#Files.

All CRUD examples using jQuery are here (not an MSDN reference, but still): http://bloggerbrij.blogspot.fr/2015/02/crud-operation-on-files-using-rest.html (credits go to Brijendra Gautam). I copy/paste code from this site for future reference:

UPLOAD A FILE:

this.AddFile = function (arrayBuffer, fileUrl, doSuccess, doError) {
    var fileData = '';
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
        fileData += String.fromCharCode(byteArray[i]);
    }

     // Send the request.
    jQuery.ajax({
        url: this.SiteUrl + "/_api/web/getfolderbyserverrelativeurl('" + this.FolderUrl + "')/Files/add(overwrite=true, url='" + fileUrl + "')",
        method: "POST",
        body: fileData,
        binaryStringRequestBody: true,
        headers: { "accept": "application/json;odata=verbose" },
        success: doSuccess,
        error: doError
    });        
}

DELETE A FILE:

this.DeleteFileByServerRelativeUrl = function (FileUrl, doSuccess, doError) {
    jQuery.ajax({
        url: this.SiteUrl + "/_api/web/getfilebyserverrelativeurl('" + FileUrl + "')",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-HTTP-Method": "DELETE"
        },
        success: doSuccess,
        error: doError
    });
}
  • thanks for your helpful replies, but my scenario requires me to create a new empty file and not to upload. – Shaked. B Jan 19 '16 at 8:19
  • I don't think you can create empty files in a doc lib. What would be your point in creating an empty file? Also: with the code provided, you can still try to create an "empy file": you just need to send 0 bytes in the content! Where in code do you see we use a file from the local system? It's all from the fileData byte array: it's up to you to fill fileData with whatever data you want. – Evariste Jan 19 '16 at 8:21
  • my goal is to let the user create a file on the sharepoint and than let him edit it from the sharepoint, without saving the file on his computer. I will try your suggestion to send 0 bytes in the content :) – Shaked. B Jan 19 '16 at 8:26
  • Yup, try with the 0 byte file... but if you want your users to edit it "from SharePoint", I assume you mean an Office file (Word, Excel) in Office Web Apps? If this is the case, don't upload a 0-byte file, but upload a .docx (or .xlsx) empty file... it's not the same. Prepare a Word file, add no content in it, save it (should be ~10KB) and extract its data as binary. You can even "hard-code" its extracted bytes in your JavaScript code!; – Evariste Jan 19 '16 at 8:43
0

If your environment is SharePoint 2013, then you can use REST API. Find MSDN references of it below.

Upload a file by using the REST API and jQuery

Working with folders and files with REST

Use XMLHttpRequest instead of jQuery as your are looking for JavaScript solution.

0
 <table>
<tr>
        <td>
            Upload: 
        </td>
        <td>
            <input id="uploadInput" type="file"  />


        </td>

    </tr>
    <tr>
        <td colspan="2" style="float:right">
<input id="uploadDocumentButton" type="Button" onclick="uploadDocument()" value="Upload Document"/>
        </td>
    </tr>
</table>
<script type="text/javascript" src="https://abcd.sharepoint.com/sites/abcd/PRTracker/SiteAssets/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://abcd.sharepoint.com/sites/abcd/PRTracker/SiteAssets/jquery.SPServices-2014.02-Copy.js"></script>
<script type="text/javascript">
 $(document).ready(function () {


});

function uploadDocument() {
    if (!window.FileReader) {
        alert("This browser does not support the HTML5 File APIs");
        return;
    }

    var element = document.getElementById("uploadInput");
    var file = element.files[0];
    var parts = element.value.split("\\");
    var fileName = parts[parts.length - 1];

    var reader = new FileReader();
    reader.onload = function (e) {
        addItem(e.target.result, fileName);
    }
    reader.onerror = function (e) {
        alert(e.target.error);
    }
    reader.readAsArrayBuffer(file);

    function addItem(buffer, fileName) {
        var call = uploadDocument(buffer, fileName);
        call.done(function (data, textStatus, jqXHR) {
            var call2 = getItem(data.d);
            call2.done(function (data, textStatus, jqXHR) {
                var item = data.d;
                var call3 = updateItemFields(item);
                call3.done(function (data, textStatus, jqXHR) {
                    var div = jQuery("#message");
                    div.text("Item added");
                });
                call3.fail(function (jqXHR, textStatus, errorThrown) {
                    failHandler(jqXHR, textStatus, errorThrown);
                });
            });
            call2.fail(function (jqXHR, textStatus, errorThrown) {
                failHandler(jqXHR, textStatus, errorThrown);
            });
        });
        call.fail(function (jqXHR, textStatus, errorThrown) {
            failHandler(jqXHR, textStatus, errorThrown);
        });
    }

    function uploadDocument(buffer, fileName) {
        var url = String.format(
            "{0}/_api/web/GetFolderByServerRelativeUrl('/sites/abcd/PRTracker/TestDocLib/abc')/Files/Add(url='{1}', overwrite=true)",
            _spPageContextInfo.webAbsoluteUrl, fileName);
alert(url);
        var call = jQuery.ajax({
            url: url,
            type: "POST",
            data: buffer,
            processData: false,
            headers: {
                Accept: "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "Content-Length": buffer.byteLength
            }
        });

        return call;
    }

    function getItem(file) {
        var call = jQuery.ajax({
            url: file.ListItemAllFields.__deferred.uri,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });

        return call;
    }

    function updateItemFields(item) {
        var now = new Date();
        var call = jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('TestDocLib')/Items(" +
                item.Id + ")",
            type: "POST",
            data: JSON.stringify({
                "__metadata": { type: "SP.Data.TestDocLibItem" },
                //Year: now.getFullYear()
            }),
            headers: {
                Accept: "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "IF-MATCH": item.__metadata.etag,
                "X-Http-Method": "MERGE"
            }
        });

        return call;
    }

    function failHandler(jqXHR, textStatus, errorThrown) {
        var response = JSON.parse(jqXHR.responseText);
        var message = response ? response.error.message.value : textStatus;
        alert("Call failed. Error: " + message);
    }
}
</script>
  • thanks for your helpful replies, but my scenario requires me to create a new empty file and not to upload. – Shaked. B Jan 19 '16 at 8:18
0
//try this to create a new file with your own content
< div > < button onclick = " createfile ()" > Click here to createfile < /button></div >  
< div id = " resultpanel " > < /div>  
<script type="text/javascript  
">   
function createfile (resultpanel)   
{  
var clientContext;  
var oWebsite;  
var oList;  
var fileCreateInfo;  
var fileContent;  
clientContext = new SP.ClientContext.get_current();  
oWebsite = clientContext.get_web();  
oList = oWebsite.get_lists().getByTitle("  
Shared Documents ");  
fileCreateInfo = new SP.FileCreationInformation();  
fileCreateInfo.set_url("  
my new file.txt ");  
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());  
fileContent = "  
The content of my new file ";  
for (var i = 0; i < fileContent.length; i++)   
{  
fileCreateInfo.get_content().append(fileContent.charCodeAt(i));  
}  
this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);  
clientContext.load(this.newFile);  
clientContext.executeQueryAsync(  
Function.createDelegate(this, successHandler),  
Function.createDelegate(this, errorHandler)  
);  
function successHandler()   
{  
resultpanel.innerHTML =  
"  
Go to the " +  
" < a href = '../Lists/Shared Documents' > document library < /a> " +  
"to see your new file.";  
}  

function errorHandler()   
{  
resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();  
}  
}  
</script >  

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.