SPJS Upload for SharePoint: Custom upload page for uploading documents to various document libraries in a site collection

Change log
August 04, 2016
New version that supports opening the EditForm after upload. This can be controlled with a variable:

// Go to EditForm after upload
var showEditFormAfterUpload = true;

Set to false to skip this feature.This new feature requires a few extra fields added to the list with the upload destination – and you must update your function call with these new fields.

If you are crating the <option> manually you must add a few extra attributes – see description in the code where you specify the <option> tags.

I got a request from Gilbert Okello regarding a custom upload solution for submitting documents to various document libraries in a site collection. This solution uses the “CopyIntoItems” method to let the user select a document from the local computer and upload it to a document library / folder within the site collection.
IMG

I must start off emphasizing that this solution requires Internet Explorer 10 or another modern browser to work. There is NO WAY you can make it work in any Internet Explorer version below 10. I have tested it in SP 2010 and SP 2013, but I guess it should work in SP 2007 as well.

The code provided at the bottom of this article builds the upload control by reading a set of predefined upload locations from a custom list. This is the code that builds the dropdown select containing the predefined options:

$(document).ready(function(){
	spjs.upload.getUploadDestinations({
		"listName":"UploadDestination",
 		"listBaseUrl":"",
 		"friendlyNameField":"Title",
 		"relPathField":"RelPath",
 		"baseUrlField":"BaseUrl",
 		"guidField":"DocLibraryGUID",
 		"editFormRelUrlField":"EditFormRelUrl",
 		"orderByField":"Title"
	});
});

listName: The GUID or the display name of the list where the upload destinations are stored.
listBaseUrl: The base URL of the list. If it is in the root site, use “”. If it is in a subsite, use “/MySubsite” or “/Sites/MySubsite” depending on your setup. The list name should NOT be included in this variable.
friendlyNameField: The FieldInternalName of the field that holds the friendly name of the destination.
relPathField: The FieldInternalName of the field that holds the relative URL to the library or folder to upload the files.
BaseUrl: Holds the base URL of the SITE where the document library is located. For example “/Sites/Site1/YourSiteName”
DocLibraryGUID: The GUID of the document library you are uploading into. View source and search for “ctx.listName” to find it.
EditFormRelUrl: The relative URL to the EditForm of your library. For example “/Sites/Site1/YourSiteName/Shared documents/Forms/EditForm.aspx”.
orderByField: The FieldInternalName of the field to sort by.

How to set up this list

Create a custom list with one additional single line of text field “RelPath”. Enter the friendly name in the Title field, and the relative path to the library or folder in the field “RelPath”.
IMG
In addition to the above fields you must add the following if you like to use the new “Go to EditForm after upload” feature.
BaseUrl: Single line of text.
DocLibraryGUID: Single line of text.
EditFormRelUrl: Single line of text.

Using this list is optional. If you like, you can enter the destination directly in the code in the <select> control with id “fileUploadTo”. If you prefer to use the manual approach, ensure you comment out the function call to “getUploadDestinations” in the code example.

The script file “spjs-utility.js” is only used for the function “getUploadDestinations” an you can remove it if you enter the destinations manually.

The code

Get the file “spjs-utility.js” from here. You will also need jQuery. Put this code in a HTML Form Web part where you want the upload control to appear – change the path to the scripts in the top of the code to match you locale files:

<!-- 
/* SPJS Upload for SharePoint
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * Copyright (c) 2013-2016 Alexander Bautz (Licensed under the MIT X11 License)
 * ---------------------------------------------
 * Include reference to:
 * jquery - http://jquery.com
 * spjs-utility.js - http://spjsfiles.com
 * ---------------------------------------------
*/
 -->
 
<script type="text/javascript" src="/SPJS/DFFS/plugins/jquery.js"></script>
<script type="text/javascript" src="/SPJS/DFFS/plugins/spjs-utility.js"></script>
<script type="text/javascript">
/*
 Pull the upload destinations from this list
 If you prefer, you can add the destinations manuelly in the <select> with id "fileUploadTo".
 In that case, comment out this function call

 Ensure the list you pull the upload destination from has all the fields specified in this article: http://wp.me/p3eibN-1nr
*/
$(document).ready(function(){
 spjs.upload.getUploadDestinations({
 "listName":"UploadDestination",
 "listBaseUrl":"",
 "friendlyNameField":"Title",
 "relPathField":"RelPath",
 "baseUrlField":"BaseUrl",
 "guidField":"DocLibraryGUID",
 "editFormRelUrlField":"EditFormRelUrl",
 "orderByField":"Title"
 });
});

// Go to EditForm after upload
var showEditFormAfterUpload = true;

</script>
<style type="text/css">
td.spjs_fileUploadLabel{
 width:150px;
 height:25px;
 font-size:16px !important;
 font-weight:bold;
 font-family:Calibri;
 color:#ffffff;
 vertical-align:middle;
 background-color:#5B9BD5;
 border:1px #41719C solid; 
 padding:3px 3px 3px 6px;
 cursor:default;
}
td.spjs_fileUploadBody{ 
 width:350px;
 font-size:16px !important;
 border:1px #41719C solid; 
 padding:3px;
 cursor:default;
}
input.spjs_fileUploadBtn{
 width:100%;
 height:33px; 
 font-size:16px !important;
 font-weight:bold;
 font-family:Calibri;
 color:#ffffff;
 border:1px #41719C solid;
 background-color:#5B9BD5; 
 cursor:pointer;
 margin:0px;
 padding:0px;
 display:none;
}
input.spjs_fileUploadBtn:hover{
 color:#5B9BD5;
 background-color:#ffffff;
}
.spjs_fileUploadSelect{
 width:100%;
 height:25px;
 background-color:#ffffff !important;
 border:none; 
 font-size:14px;
}
.spjs_empty{
 border:1px #FF0000 dashed !important;
}
</style>
<table cellpadding="0" cellspacing="5" style="border-collapse:separate;">
 <tr>
 <td class="spjs_fileUploadLabel">File</td>
 <td class="spjs_fileUploadBody">
 <input type="file" id="filePicker" style="width:100%;padding:0px;">
 <span style="display:none;color:red;font-size:12px;">Your browser is not supported!<br>Use Internet Explorer 10 or another modern browser.</span>
 </td>
 </tr>
 <tr>
 <td class="spjs_fileUploadLabel">Upload To</td>
 <td class="spjs_fileUploadBody"> 
 <select id="fileUploadTo" class="spjs_fileUploadSelect">
 <!--
 // guid attribute must be guid of destination document library
 // baseurl attribute must be baseURL of site wher the document library is located
 // editformurl attribute must be relative url to the EditForm of this library
 <option value="">Select destination</option>
 <option guid='' baseurl='/Upload' editformurl='/Upload/Forms/EditForm.aspx' value="/Upload/Folder1">Folder 1</option>
 <option guid='' baseurl='/Upload' editformurl='/Upload/Forms/EditForm.aspx' value="/Upload/Folder2">Folder 2</option>
 --> 
 </select>
 </td>
 </tr>
 <tr>
 <td></td>
 <td class="spjs_fileUploadBtn">
 <input id="uploadFileBtn" type="button" class="spjs_fileUploadBtn" onclick="spjs.upload.submitFile();" value="Submit" />
 <span id="uploadError" style="display:none;color:red;"></span>
 </td>
 </tr>
</table>
<script type="text/javascript">

/******************************************************
 Do not change anything below this line
*******************************************************/
var spjs = spjs || {};

spjs.upload = {
 "version":"1.1",
 "versionDate":"August 04, 2016",
 "data":{"fileDataStr":""},
 "handleFileSelect":function(evt){
 // Modified from http://jsfiddle.net/eliseosoto/JHQnk/
 var files = evt.target.files, file = files[0], reader;
 if(files && file){
 reader = new FileReader();
 reader.onload = function(readerEvt) {
 var binaryString = readerEvt.target.result;
 spjs.upload.data.fileDataStr = binaryString.substring(binaryString.indexOf(",")+1);
 $("#uploadFileBtn").show();
 };
 reader.readAsDataURL(file);
 }
 },
 "submitFile":function() {
 if($("#fileUploadTo").val() === ""){
 $("#fileUploadTo").addClass("spjs_empty");
 return;
 }else{
 $("#fileUploadTo").removeClass("spjs_empty");
 }
 var filePath, fileName, destination, b;
 filePath = $("#filePicker").val();
 fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
 destination = location.protocol+"//"+location.host+$("#fileUploadTo").val()+"/"+fileName;
 b = [];
 b.push("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
 b.push("<soap:Body>");
 b.push("<CopyIntoItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>");
 b.push("<SourceUrl>" + fileName + "</SourceUrl>");
 b.push("<DestinationUrls>");
 b.push("<string>"+destination+"</string>");
 b.push("</DestinationUrls>");
 b.push("<Fields>");
 b.push("<FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='"+fileName+"' />");
 b.push("</Fields>");
 b.push("<Stream>"+spjs.upload.data.fileDataStr+"</Stream>");
 b.push("</CopyIntoItems>");
 b.push("</soap:Body>");
 b.push("</soap:Envelope>");
 $.ajax({
 url: "/_vti_bin/copy.asmx",
 beforeSend: function (xhr) { xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems"); },
 type: "POST",
 dataType: "xml",
 data: b.join(""),
 complete: spjs.upload.processResult,
 contentType: "text/xml; charset=\"utf-8\""
 });
 },
 "processResult":function(data, status) {
 var errorCode, errorMessage;
 errorCode = $(data.responseText).find("CopyResult").attr("ErrorCode");
 errorMessage = $(data.responseText).find("CopyResult").attr("ErrorMessage");
 if(errorCode !== "Success"){
 $("#uploadFileBtn").fadeOut(400,function(){
 $("#uploadError").html("Ensure the selected destination exists!<br><br>Error message: "+errorMessage).show();
 setTimeout(function(){
 $("#uploadError").fadeOut();
 $("#fileUploadTo").val("");
 $("#uploadFileBtn").fadeIn();
 },10000);
 }); 
 }else{
 $("#uploadFileBtn").attr("disabled","disabled").val("File successfully uploaded");
 if(typeof showEditFormAfterUpload !== "undefined" && showEditFormAfterUpload){
 var fileDir = $(data.responseText).find("CopyResult").attr("DestinationUrl");
 var docLibBaseUrl = $("#fileUploadTo option:selected").attr('baseurl');
 var docLibGuid = $("#fileUploadTo option:selected").attr('guid');
 var docLibEditFormUrl = $("#fileUploadTo option:selected").attr('editformurl')
 var fileMetadata = spjs.utility.queryItems({"listName":docLibGuid,"listBaseUrl":docLibBaseUrl,"query":"<Where><Eq><FieldRef Name='EncodedAbsUrl' /><Value Type='Text'>"+fileDir+"</Value></Eq></Where>","scope":"RecursiveAll","viewFields":["FileLeafRef","FileDirRef"]})
 if(fileMetadata.count > 0){
 var id = fileMetadata.items[0].ID;
 SP.UI.ModalDialog.showModalDialog({"url":makeAbsUrl(docLibEditFormUrl+"?ID="+id+"&Mode=Upload")});
 }
 }
 setTimeout(function(){
 $("#uploadFileBtn").fadeOut(400,function(){
 $(this).removeAttr("disabled").val("Submit");
 $("#fileUploadTo").val("");
 })
 },3000);
 $("#filePicker").val("");
 }
 },
 "getUploadDestinations":function(args){
 var res, q, b;
 b = ["<option value=''>Select destination</option>"];
 q = "<Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where><OrderBy><FieldRef Name='"+args.orderByField+"' /></OrderBy>";
 res = spjs_QueryItems({"listName":args.listName,"listBaseUrl":args.listBaseUrl,"query":q,"viewFields":[args.friendlyNameField,args.relPathField,args.baseUrlField,args.guidField,args.editFormRelUrlField]});
 $.each(res.items,function(i,item){
 b.push("<option editformurl='"+item.EditFormRelUrl+"' baseurl='"+item.BaseUrl+"' guid='"+item.DocLibraryGUID+"' value='"+item[args.relPathField]+"'>"+item[args.friendlyNameField]+"</option>")
 });
 $("#fileUploadTo").html(b.join(""));
 }
};

if(window.File && window.FileReader && window.FileList && window.Blob){
 document.getElementById('filePicker').addEventListener('change', spjs.upload.handleFileSelect, false);
}else{
 $("#filePicker").hide().next().show();
 $("#fileUploadTo").hide(); 
}
</script>

Post questions and feedback in the comments section below, and if you use this solution, please consider sending me a few beers by clicking the “beer button” in the top right corner of this page.

Enjoy,
Alexander

62 thoughts on “SPJS Upload for SharePoint: Custom upload page for uploading documents to various document libraries in a site collection”

  1. Hi Alexander,
    Thanks!!!

    When I upload the script to the source editor of the HTML form web part, i get an error: “Cannot retrieve properties at this time”.

    Am i missing something?

    1. This has nothing to do with this script I think, try using compatibility mode in the browser. You can also add the script to a file and link it from a Content Editor Web Part using the content link option.

      Alexander

      1. HI,

        To add to my earlier post:
        It worked with Firefox.
        Didn’t work with IE (I am not getting the ‘submit’ button).

        It didn’t work with Chrome. Gives the following error:
        “Ensure the selected destination exists!
        Error message: undefined”

        Gilbert

  2. Hi,

    I have implements as described, however I still see the following error even though I am using Internet Explorer 11:

    Your browser is not supported!
    Use Internet Explorer 10 or another modern browser.

      1. No sites listed in Compatibility view settings.

        I also checked the site in Google Chrome (Version 31.0.1650.63 m) and experienced the same issue.

      1. SharePoint 2010 (14.0.7015.1000)

        F12 Settings are:

        Document Mode: 8 (Default)
        User Agent String: Default

        This is strange because there are definitely no Compatibility mode sites and the ‘Display Intranet Sites in Compatibility view’ setting is not ticked!

      2. The problem is that SharePoint forces this document mode in the master page.

        Does it work if you change it to IE10? – still strange that Chrome did not work though…

        Alexander

      3. Doesn’t change if I change it to ’10’ for either the Document Mode or the Agent String

      1. Hii,

        I have use the RelPath but the problem is over there when we select the file then the Upload to option is blank ie List is not connected

        Thanks
        Deepak C

  3. $(document).ready(function () {
    test();
    });

    /******************************************************
    Do not change anything below this line
    *******************************************************/

    function test() {
    var spjs = spjs || {};

    spjs.upload = {
    “version”: “1.0”,
    “versionDate”: “December 8, 2013”,
    “data”: { “fileDataStr”: “” },
    “handleFileSelect”: function (evt) {

    var files = evt.target.files, file = files[0], reader;
    if (files && file) {
    reader = new FileReader();
    reader.onload = function (readerEvt) {
    var binaryString = readerEvt.target.result;
    spjs.upload.data.fileDataStr = binaryString.substring(binaryString.indexOf(“,”) + 1);
    $(“#uploadFileBtn”).show();
    };
    reader.readAsDataURL(file);
    }
    },
    “submitFile”: function () {
    if ($(“#fileUploadTo”).val() === “”) {
    $(“#fileUploadTo”).addClass(“spjs_empty”);
    return;
    } else {
    $(“#fileUploadTo”).removeClass(“spjs_empty”);
    }
    var filePath, fileName, destination, b;
    filePath = $(“#filePicker”).val();
    fileName = filePath.substring(filePath.lastIndexOf(“\\”) + 1);
    destination = location.protocol + “//” + location.host + $(“#fileUploadTo”).val() + “/” + fileName;
    b = [];
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“” + fileName + “”);
    b.push(“”);
    b.push(“” + destination + “”);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“” + spjs.upload.data.fileDataStr + “”);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    $.ajax({
    url: “/_vti_bin/copy.asmx”,
    beforeSend: function (xhr) { xhr.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems”); },
    type: “POST”,
    dataType: “xml”,
    data: b.join(“”),
    complete: spjs.upload.processResult,
    contentType: “text/xml; charset=\”utf-8\””
    });
    },
    “processResult”: function (data, status) {
    var errorCode, errorMessage;
    errorCode = $(data.responseText).find(“CopyResult”).attr(“ErrorCode”);
    errorMessage = $(data.responseText).find(“CopyResult”).attr(“ErrorMessage”);
    if (errorCode !== “Success”) {
    $(“#uploadFileBtn”).fadeOut(400, function () {
    $(“#uploadError”).html(“Ensure the selected destination exists!Error message: ” + errorMessage).show();
    setTimeout(function () {
    $(“#uploadError”).fadeOut();
    $(“#fileUploadTo”).val(“”);
    $(“#uploadFileBtn”).fadeIn();
    }, 10000);
    });
    } else {
    $(“#uploadFileBtn”).attr(“disabled”, “disabled”).val(“File successfully uploaded”);
    setTimeout(function () {
    $(“#uploadFileBtn”).fadeOut(400, function () {
    $(this).removeAttr(“disabled”).val(“Submit”);
    })
    }, 3000);
    $(“#filePicker”).val(“”);
    }
    },
    “getUploadDestinations”: function (args) {
    var res, q, b;
    b = [“Select destination”];
    q = “”;
    res = spjs_QueryItems({ “listName”: args.listName, “listBaseUrl”: args.listBaseUrl, “query”: q, “viewFields”: [args.friendlyNameField, args.relPathField] });
    $.each(res.items, function (i, item) {
    b.push(“” + item[args.friendlyNameField] + “”)
    });
    $(“#fileUploadTo”).html(b.join(“”));
    }
    };

    if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById(‘filePicker’).addEventListener(‘change’, spjs.upload.handleFileSelect, false);
    } else {
    $(“#filePicker”).hide().next().show();
    $(“#fileUploadTo”).hide();
    }
    }

    File

    Your browser is not supported!Use Internet Explorer 10 or another modern browser.

    Upload To

    Select destinationFolder 1Folder 2

    When We debug the script so that the spjs.upload.submitFile() is undefined so reply me as soon as possible

  4. Hello Alex,

    How we can upload multiple file in you script and shows these file into below if you have time please send me the code it’s very urgent for me……….

    Thanks
    Deepak chauhan

  5. Hi Alexander,

    I’ve tried your code and works marvelous, I still have one question though, let’s say that my documents library has a field called “special Id” which I have stored in a SQL database and I’m getting information listed from SQL in my webpage, is it possible to take this “special Id” into the upload document function so the value get’s stored each time a user uploads a document?

    Thanks in advance for your help!
    Carlos

    1. Hi,
      You should be able to add extra fields to the upload code. Change these lines:

      b.push("<Fields>");
      b.push("<FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='"+fileName+"' />");
      b.push("</Fields>");

      like this:

      b.push("<Fields>");
      b.push("<FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='"+fileName+"' />");
      b.push("<FieldInformation Type='Text' DisplayName='Your field name' InternalName='YourFieldInternalName' Value='"+the_variable_with_the_id+"' />");
      b.push("</Fields>");

      Alexander

  6. var spjs = spjs || {};

    spjs.upload = {
    “version”:”1.0″,
    “versionDate”:”December 8, 2013″,
    “data”:{“fileDataStr”:””},
    “handleFileSelect”:function(evt){
    var files = evt.target.files, file = files[0], reader;
    if(files && file){
    reader = new FileReader();
    reader.onload = function(readerEvt) {
    var binaryString = readerEvt.target.result;
    spjs.upload.data.fileDataStr = binaryString.substring(binaryString.indexOf(“,”)+1);
    $(“#uploadFileBtn”).show();
    };
    reader.readAsDataURL(file);
    }
    },
    “submitFile”:function() {
    if($(“#fileUploadTo”).val() === “”){
    $(“#fileUploadTo”).addClass(“spjs_empty”);
    return;
    }else{
    $(“#fileUploadTo”).removeClass(“spjs_empty”);
    }
    var filePath, fileName, destination, b;
    filePath = $(“#filePicker”).val();
    fileName = filePath.substring(filePath.lastIndexOf(“\\”)+1);
    destination = location.protocol+”//”+location.host+”/clientes/excondemo/Control%20de%20Documentos/”+fileName;
    b = [];
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“” + fileName + “”);
    b.push(“”);
    b.push(“”+destination+””);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    b.push(“”+spjs.upload.data.fileDataStr+””);
    b.push(“”);
    b.push(“”);
    b.push(“”);
    $.ajax({
    url: “/_vti_bin/copy.asmx”,
    beforeSend: function (xhr) { xhr.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems”); },
    type: “POST”,
    dataType: “xml”,
    data: b.join(“”),
    complete: spjs.upload.processResult,
    contentType: “text/xml; charset=\”utf-8\””
    });
    },
    “processResult”:function(data, status) {
    var errorCode, errorMessage;
    errorCode = $(data.responseText).find(“CopyResult”).attr(“ErrorCode”);
    errorMessage = $(data.responseText).find(“CopyResult”).attr(“ErrorMessage”);
    if(errorCode !== “Success”){
    $(“#uploadFileBtn”).fadeOut(400,function(){
    $(“#uploadError”).html(“Ensure the selected destination exists!Error message: “+errorMessage).show();
    setTimeout(function(){
    $(“#uploadError”).fadeOut();
    $(“#fileUploadTo”).val(“”);
    $(“#uploadFileBtn”).fadeIn();
    },10000);
    });
    }else{
    $(“#uploadFileBtn”).attr(“disabled”,”disabled”).val(“File successfully uploaded”);
    setTimeout(function(){
    $(“#uploadFileBtn”).fadeOut(400,function(){
    $(this).removeAttr(“disabled”).val(“Submit”);
    })
    },3000);
    $(“#filePicker”).val(“”);
    }
    }
    };

    this is my code…. it’s works but the file is empty in librery with out data inside.

      1. I misspelled – I meant FILE types – is this what you meant also?

        Can you hit F12 in IE and tell me the document mode and user agent string that shows in the bottom button in the left side of the developer console.

        Alexander

    1. OK – Good,
      The problem may be the document mode. I’m not sure why this document mode is applied, but try changing it to 10 – and also the user agent string to 10.

      Do you have other code that could force this document mode? – it refers to IE v5 from 1999…

      Alexander

  7. Totally confused. Are there two scripts to load? The getUploadDestination script is not anywhere in the list of js files–…”Get the file “spjs-utility.js” from here”

    $(document).ready(function(){
    spjs.upload.getUploadDestinations({
    “listName”:”UploadDestination”,
    “listBaseUrl”:””,
    “friendlyNameField”:”Title”,
    “relPathField”:”RelPath”,
    “orderByField”:”Title”
    });

  8. What if I have additional data fields in the Document library that I want to update when this file is loaded … can this be done as well with this code? The fields may be i.e. Material Type, etc.

  9. I have the following code implementing and I do not understand what format I need to enter in for the value.. please assume I am only interested in one specific Document Library so this value can be hard-coded… the URL for my DEV environment is

    http://itsusmpw00799:56789/prd/hcctesting/PharmSLT_Meetings_Materials/Forms/AllItems.aspx

    I am struggling to get this work.

    What other pieces of code need to be customized to get this to work and what references to JS do I need if all the scripts are emebedded?

  10. Can you explain why you took a substring of the file reader output in the line “spjs.upload.data.fileDataStr = binaryString.substring(binaryString.indexOf(“,”)+1);”

    I ask because I’m trying to figure out why the solution does not work for Microsoft PowerPoint files using IE10 and SP2010 at my workplace. I have no issues on my own SP2010 website using IE11.

    1. This is done to strip off the part to the left of the comma – like this example string for an image:

      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAGCAYAAAAc2cSCAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNvyMY98AAAAxSURBVChTY/j//z9R+G88iEIVQ+HgwiCNZGmGaSRZM7JGkjSjayRaMzaNIIyq7j8DACKS/6ll06b/AAAAAElFTkSuQmCC"

      Alexander

  11. Hi Alex, thanks for sharing this brilliant work! I’m in the process of testing the above solution for our intranet with multiple document libraries. Few things that I would love to know is:
    1. How can we force reset the ‘File Select’ & ‘Upload Destination’ fields after every instance regardless of final outcome?
    2. How can we get prompted to populate ‘REQUIRED’ metadata following the successful file upload? – Basically the file upload function works flawlessly but would love to see the EDIT properties form prompted to force the users to do the right thing & check-in.
    3. Bit over optimistic – I’ve noticed that spjs-utility.js has functions to call CASCADED drop-downs. Could we use this to perform selective lookup? Say, you choose a upload destination ‘Restricted’ upon which, 3rd field called ‘Choose’ with dropdown choices say HR / Finance / Corporate should become available. Correct me if I’ve wrong assumption. Really appreciate your time and help. Cheers!

  12. Hi,
    1: You can reset the upload to by changing the function “processResult” and adding this to the “success” function. See the “error” function a few lines up for reference.

    $("#fileUploadTo").val("");

    2: This is currently not built in, but you can add something like this to the “success” function in “processResult” – after this line:

    $("#uploadFileBtn").attr("disabled","disabled").val("File successfully uploaded");
    var fileDir = $(data.responseText).find("CopyResult").attr("DestinationUrl");
    var fileMetadata = spjs.utility.queryItems({"listName":$("#fileUploadTo option:selected").text(),"query":"<Where><Eq><FieldRef Name='EncodedAbsUrl' /><Value Type='Text'>"+fileDir+"</Value></Eq></Where>","scope":"RecursiveAll","viewFields":["FileLeafRef","FileDirRef"]})
    if(fileMetadata.count > 0){
        var id = fileMetadata.items[0].ID;
        var path = fileMetadata.items[0].FileDirRef.split(";#")[1];
        SP.UI.ModalDialog.showModalDialog({"url":makeAbsUrl("/"+path+"/Forms/EditForm.aspx?ID="+id)});
    }

    Please note that this will not work in SP2007 as the “showModalDialog” function is not built in.

    Also note that this code example will only work if:
    * You use the display name of the document library in the “option text” / Title in the <select>
    * Your document library is in the same site as the upload control.

    3: The cascaded dropdown solution I have created is for SharePoint forms and cannot be used here.

    Unfortunately I don’t have time to add this functionality, but as you have access to he actual <select> in the code you can build your own cascading logic if you like – you are free to alter the code if you want to give it a go.

    You can also add the destinations manually as <option> in the <select> – and you can use <optgroup> to group the different destinations.

    Alexander

  13. Alex, brilliant! really appreciate your time and help.

    The file edit form.aspx following the file upload worked great! in my SP O365 test site collection as I had the list names and config exactly to meet the requirements in your response to pt.2. Also, EditForm in Upload mode (Mode=Upload) works just a treat as it allows to CheckIn the file.

    SP.UI.ModalDialog.showModalDialog({“url”:makeAbsUrl(“/”+path+”/Forms/EditForm.aspx?Mode=Upload&ID=”+id)})

    But, in our production SP O365, I have a DestinationList created as per your guidance in this article. Again, it works great for file upload. I’m failing to get EditForm.aspx following the upload. In relation to this:
    a. will the above code (your reply to pt.2) work if there is a space in the destination library name? I’ve confirmed the Display name = Library Name. As an example we have a document library called ‘Information Technology’ and ‘Human Resources’
    b. if we have a secured folder with-in a library with different permission and if I’m using the ‘Select Destination’ list to define the file upload path then, unfortunately, as you have pointed out, I cant get the editform.aspx using the above method. So, wondering if there is any other ways to achieve the same result?
    Can we somehow obtain the URL & ID of recently uploaded file by reverse lookup and then pass them to EditForm.aspx? Was thinking something along SPServices.SPGetLastItemID!?
    Again, appreciate your time. Your articles are very helpful for many SharePoint Admins like myself.
    cheers

  14. Hi Alex,
    is it possible to have two upload fields at single page?
    The usecase is that there are no “select destination” section but fixed. One upload field saves files to one document library, second upload field saved different type of document to another document library.
    Thanks
    Michal

    1. I looked at the code and it doesn’t look like this will be possible because the html controls ID is not adapted for using multiple instances in one page.

      You can try modifying the code to add a parameter “instanceID”:”an_unique_string” in the argument passed to the function, and then appending this string to all the ID’s – like “uploadFileBtn” to ensure all controls are unique even if you add the function multiple times.

      Alexander

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.