Instantly share code, notes, and snippets.
Last active
August 29, 2015 14:02
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
Save Salvodif/ec84dd3400b4abb2ca22 to your computer and use it in GitHub Desktop.
Get raw data from file or sharepoint then create a new file on sp library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function succeeded ( filename ) { | |
var statusId = SP.UI.Status.addStatus ( filename, "The file has been copied.", true ); | |
SP.UI.Status.setStatusPriColor ( statusId, 'green' ); | |
setTimeout ( function ( ) { SP.UI.Status.removeStatus ( statusId ); }, 4000 ); | |
} | |
function failed ( filename ) { | |
var statusId = SP.UI.Status.addStatus ( filename, "The file hasn't been copied.", true ); | |
SP.UI.Status.setStatusPriColor ( statusId, 'red' ); | |
setTimeout ( function ( ) { SP.UI.Status.removeStatus ( statusId ); }, 4000 ); | |
} | |
function getParam ( name ) { | |
if ( name = ( new RegExp ( '[?&]' + encodeURIComponent ( name ) + '=([^&]*)' ) ).exec ( location.search ) ) | |
return decodeURIComponent ( name [ 1 ] ); | |
return ""; | |
} | |
function getBuffer ( options, typeOfBuffer ) { | |
/// <summary>Get the file raw data from the file to upload or from Sharepoint.</summary> | |
/// <param name="options" type="Object">Contains all the informations that the functions needs to work.</param> | |
/// <param name="typeOfBuffer" type="Number">0 to get the raw data from the file - 1 to get the raw data from SharePoint.</param> | |
/// <returns type="Number">The deferred status.</returns> | |
var def = $.Deferred ( ); | |
switch ( typeOfBuffer ) { | |
case 0 : | |
getFileBuffer ( ); | |
break; | |
case 1 : | |
getFromSharepoint ( ); | |
break; | |
default : | |
def.reject ( "No typeOfBuffer selected" ); | |
} | |
function getFileBuffer ( ) { | |
if ( options.file === undefined && options.file === null ) { | |
return def.reject ( "File buffer error" ); | |
} | |
var reader = new FileReader ( ); | |
reader.onload = function ( e ) { | |
var fileData = ''; | |
var byteArray = new Uint8Array ( e.target.result ); | |
for ( var i = 0; i < byteArray.byteLength; i++ ) { | |
fileData += String.fromCharCode ( byteArray [ i ] ); | |
} | |
def.resolve ( | |
{ | |
dst : options.dst, | |
buffer : fileData, | |
filename : options.file.name | |
} | |
); | |
}; | |
reader.onerror = function ( e ) { | |
console.debug ( e.target.error ); | |
def.reject ( e.filename ); | |
}; | |
reader.readAsArrayBuffer ( options.file ); | |
return def.promise ( ); | |
} | |
function getFromSharepoint ( ) { | |
var currentProposal = options.selectedProposal; | |
if ( currentProposal === undefined ) { | |
return def.reject ( "From Sharepoint buffer error" ); | |
} | |
var x = { | |
absUrl : _spPageContextInfo.siteAbsoluteUrl, | |
relUrl : _spPageContextInfo.webServerRelativeUrl, | |
proposal : currentProposal, | |
filename : options.filename | |
}; | |
x.srcUrl = _.str.sprintf ( "%(absUrl)s/_api/web/getFileByServerRelativeUrl('%(proposal)s')/$value", x ); | |
console.debug ( x ); | |
$.getScript ( _spPageContextInfo.scriptbase + "/SP.RequestExecutor.js", function ( ) { | |
var executor = new SP.RequestExecutor ( x.absUrl ); | |
var info = { | |
url : x.srcUrl, | |
method : "GET", | |
binaryStringResponseBody : true, | |
success : function ( data ) { | |
def.resolve ( { | |
dst : options.dst, | |
buffer : data.body, | |
filename : x.filename | |
} ); | |
}, | |
error : function ( e ) { | |
console.debug ( e.target.error ); | |
def.reject ( x.filename ); | |
} | |
}; | |
executor.executeAsync ( info ); | |
} ); | |
} | |
return def.promise ( ); | |
} | |
function saveProposal ( fileToSave ) { | |
var def = $.Deferred ( ); | |
var buffer = fileToSave.buffer; | |
var x = { | |
absUrl : _spPageContextInfo.siteAbsoluteUrl, | |
webRelativeUrl : _spPageContextInfo.webServerRelativeUrl, | |
dst : fileToSave.dst, | |
filename : fileToSave.filename | |
}; | |
x.dstUrl = _.str.sprintf ( "%(absUrl)s/%(dst)s/_api/web/getFolderByServerRelativeUrl('/%(webRelativeUrl)s/%(dst)s/LibUploadedFiles')/Files/add(url='%(filename)s',overwrite=true)", x ); | |
$.getScript ( _spPageContextInfo.scriptbase + "/SP.RequestExecutor.js", function ( ) { | |
var executor = new SP.RequestExecutor ( x.absUrl ); | |
var destInfo = { | |
url : x.dstUrl, | |
method : "POST", | |
headers : { | |
"Accept" : "application/json; odata=verbose", | |
"X-RequestDigest" : $ ( "#__REQUESTDIGEST" ).val ( ) | |
}, | |
contentType : "application/json;odata=verbose", | |
binaryStringRequestBody : true, | |
body : buffer, | |
success : function ( data ) { | |
console.debug ( data ); | |
def.resolve ( x.filename ); | |
}, | |
error : function ( err ) { | |
console.debug ( err ); | |
def.reject ( x.filename ); | |
} | |
}; | |
executor.executeAsync ( destInfo ); | |
} ); | |
return def.promise ( ); | |
} | |
( function ( my ) { | |
my.Proposal = function ( ) { | |
this.Id = ""; | |
this.Title = ""; | |
this.Modified = ""; | |
this.Author = ""; | |
this.TypesOfContent = [ ]; | |
this.FileRef = ""; | |
}; | |
} ) ( DTOs = DTOs || { } ); | |
( function ( my ) { | |
function getData ( viewCallback ) { | |
SP.SOD.executeFunc ( 'sp.js', 'SP.ClientContext', function ( ) { | |
$.getScript ( _spPageContextInfo.scriptbase + "/SP.Taxonomy.js", function ( ) { | |
var ctx = new SP.ClientContext ( _spPageContextInfo.siteAbsoluteUrl ); | |
var list = ctx.get_web ( ).get_lists ( ).getByTitle ( "Opportunity Center Documents" ); | |
var query = new SP.CamlQuery ( ); | |
query.set_viewXml ( "<View><RowLimit>10</RowLimit></View>" ); | |
var items = list.getItems ( query ); | |
ctx.load ( items, "Include(Id, Title, Modified, TypeOfContent, Modified_x0020_By, FileRef)" ); | |
ctx.executeQueryAsync ( Function.createDelegate ( this, function ( ) { | |
var itemsEnum = items.getEnumerator ( ); | |
var buffer = [ ]; | |
while ( itemsEnum.moveNext ( ) ) { | |
var item = itemsEnum.get_current ( ); | |
var proposal = new DTOs.Proposal ( ); | |
proposal.Id = item.get_id ( ); | |
proposal.Title = item.get_item ( "Title" ); | |
proposal.Modified = item.get_item ( "Modified" ); | |
proposal.Author = item.get_item ( "Modified_x0020_By" ); | |
proposal.FileRef = item.get_item ( "FileRef" ); | |
var contentOfType = item.get_item ( 'TypeOfContent' ); | |
for ( var i = 0; i < contentOfType.get_count ( ); i++ ) { | |
var tag = contentOfType.getItemAtIndex ( i ); | |
var label = tag.get_label ( ); | |
var id = tag.get_termGuid ( ); | |
proposal.TypesOfContent.push ( label ); | |
} | |
buffer.push ( proposal ); | |
} | |
viewCallback ( buffer ); | |
} | |
), Function.createDelegate ( this, function ( sender, args ) { | |
console.error ( "Retrieving items failed." ); | |
console.error ( args.get_message ( ) ); | |
} ) ); | |
} ); | |
} ); | |
} | |
// View Model | |
my.Proposals = function ( ) { | |
var subSiteTitle = ""; | |
var newProposalFiles; | |
var nid = 0; | |
_spPageContextInfo.scriptbase = _spPageContextInfo.siteAbsoluteUrl + "/" + _spPageContextInfo.layoutsUrl; | |
var _viewModel = { | |
loading : ko.observable ( true ), | |
items : ko.observableArray ( [ ] ), | |
noItems : ko.observable ( ), | |
itemsChecked : ko.observableArray ( ), | |
fileToUpload : ko.observable ( false ) | |
}; | |
_viewModel.enableButton = ko.computed ( function ( ) { | |
if ( _viewModel.itemsChecked ( ).length <= 0 && _viewModel.fileToUpload ( ) === false ) | |
return false; | |
return true; | |
} ); | |
_viewModel.onFileSelectedEvent = function ( vm, evt ) { | |
newProposalFiles = evt.target.files; | |
_viewModel.fileToUpload ( true ); | |
}; | |
_viewModel.uploadProposal = function ( ) { | |
nid = SP.UI.Notify.addNotification ( '<span>Coping in progress</span>', true ); | |
var i; | |
var currentFile; | |
var filename; | |
var selectedItems = _viewModel.itemsChecked ( ); | |
// from SP to SP | |
for ( i = 0; i < selectedItems.length; i++ ) { | |
currentFile = selectedItems [ i ]; | |
filename = currentFile.substring ( currentFile.lastIndexOf ( "/" ) + 1 ); | |
getBuffer ( { | |
filename : filename, | |
selectedProposal : currentFile, | |
dst : subSiteTitle | |
}, 1 ).then ( function ( x ) { | |
saveProposal ( x ).then ( | |
function ( e ) { succeeded ( e ); }, | |
function ( e ) { failed ( e ); } | |
); | |
}, | |
function ( e ) { failed ( e ); } ); | |
} | |
// from file to SP | |
if ( newProposalFiles !== undefined && newProposalFiles !== null ) { | |
for ( i = 0; i < newProposalFiles.length; i++ ) { | |
currentFile = newProposalFiles [ i ]; | |
getBuffer ( { | |
file : currentFile, | |
dst : subSiteTitle | |
}, 0 ).then ( function ( x ) { | |
saveProposal ( x ).then ( | |
function ( e ) { succeeded ( e ); }, | |
function ( e ) { failed ( e ); } | |
), | |
function ( e ) { failed ( e ); }; | |
} ); | |
} | |
} | |
SP.UI.Notify.removeNotification ( nid ); | |
}; | |
function applyView ( buffer ) { | |
_viewModel.noItems ( buffer.length <= 0 ? true : false ); | |
_viewModel.items ( buffer ); | |
_viewModel.loading ( false ); | |
} | |
// main point | |
( function ( ) { | |
subSiteTitle = "TestSubSite"; //getParam ( "subSiteTitle" ); | |
if ( subSiteTitle === "" ) | |
return; | |
getData ( applyView ); | |
} ) ( ); | |
return _viewModel; | |
}; | |
} ) ( Modals = Modals || { } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment