files.save_one Multifile Sample

Submitted by Jerad Whitaker on 06 Sep 2012 14:03
rating: 0

Description

This page allows you to either use the browser selection to pick multiple files to save or drag and drop files into the drop zone.

Sample Code

<html><title>Wikidot Files Add</title>
<head>
 
<style type="text/css">
#fileselect{width:60%; height:440px;float:left;}
#formdata{width:40%; height:440px;float:right;}
</style>
<meta charset="UTF-8">
<!-- mimic.js must be on a secure server for this to work (thanks Tsangk!) -->
<script src="https://php-api.wikidot.com/local--files/files:sample-files/mimic.js"></script>
</head>
<body onload="display('hide')">
<style>  .thumb {height: 75px;    border: 1px solid #000;    margin: 10px 5px 0 0;  }
</style>
<h2>Add multiple files to a wikidot page</h2>
<div style="padding: 3px; align:center;
border: 2px solid #00F;
border-radius: 8px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;">
<form>
<label for="apikey" style="padding: 3px; display: block;">API Key:</label>
<input type="text" id="apikey" size = "50" maxlength = "50" /></br>
<label for="sitename" style="padding: 3px; display: block;">Site Name:</label>
<input type="text" id="sitename" size = "20" maxlength = "30" /></br>
<label for="pagename" style="padding: 3px; display: block;">Page Name:</label>
<input type="text" id="pagename" size = "20" maxlength = "30" /></br>
</form></br>
<input type="button" value="Set Key" onclick="getFormData()"> </br>
</div></br>
<div id="fileselect">
<div style="width:220px;height:20px;border:1px solid blue;"
id="drop_zone">Drop files here</div>
<output id="droplist"></output>
</br></br>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
</br></br>
</div>
<div id="formdata" style="white-space: normal; word-wrap: break-word;">
Form Inputs:</br>
<output id="form"></output>
</div>
 
<script>
var requestobj;    //api request object
var apisite;        //constructed from form data
var apikey;        //user key input on form
var domain;        //site domain input on form
var sitename;    //site name input on form
var pagename;    //page name that gets the added files, input on form
var method = "files.save_one"; //api requested method
//////set listeners
document.getElementById('files').addEventListener('change', handleFileSelect, false);
document.getElementById('apikey').addEventListener('change', function () {CheckZero (document.getElementById('apikey'))}, true);
document.getElementById('sitename').addEventListener('change', function () {CheckZero (document.getElementById('sitename'))}, true);
document.getElementById('pagename').addEventListener('change', function () {CheckZero (document.getElementById('pagename'))}, true);
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileDrop, false);
 
function CheckZero(field) //check if form field is blank
{    if(field.value == "") {
        display('hide');
        return true;}
    else return false;
}
 
function display(action) //toggles the display of the files selectors
{    if (action == 'show')  { //shows the selectors to allow addition of files
        document.getElementById('fileselect').style.display = "block";}
    if (action == 'hide')  { //hides the selectors to not allow adding of files
        document.getElementById('fileselect').style.display = "none";}  
}
 
function getFormData() //gets the API info from the form and constructs the API caller data
{    var ak = document.getElementById('apikey');
    apikey = ak.value;
    var sn = document.getElementById('sitename');
    sitename = sn.value;
    var pn = document.getElementById('pagename');
    pagename = pn.value;
    apisite = "https:\/\/" + "user" + ":" + apikey + "@" + sitename + ".wdfiles.com\/xml-rpc-api.php";
    document.getElementById('form').innerHTML = apikey + "</br>" + 
                sitename + "</br>" + pagename + "</br>" + apisite;
    if(!CheckZero(ak) &&  !CheckZero(sn) && !CheckZero(pn)) display('show');
    else display('hide');
}
 
function GetData(urldata)    //takes the return from readAsDataURL and strips out the data URI header
{//the read function returns base64 data URI by default
//replace the header end characters '%2C' with a non base64 character '&'
    var temp = urldata.replace("%2C", "&");
//split the string at the end of the header
    var halves = temp.split("&");
//keep the part of the string after the header, this should be only the base64 file content
    var retstring = halves[1];
//check to see if split was successful, if not, return an empty string so API call can complete
    var undef;
    if(retstring === undef) retstring = "";
 
    return retstring;
}
 
function handleFileSelect(evt) { //handler for text box selected files
    var files = evt.target.files; // FileList object
    DoAPIFileSaveOne(evt, "list", files);
}
 
function DoAPIFileSaveOne(evt, sellist, files) { //common save_one handler
    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            '</li>');   
    // Only process image and pdf files.
        if (!f.type.match('image.*') && f.type != "application/pdf"){continue;} //file was not an image or pdf
            if (f.type == "application/pdf"){//process pdf files
                var reader = new FileReader();
                // Closure to capture the file information.
                reader.onload = (function(theFile) {return function(e) {
                    var fname = escape(theFile.name);
                    var b64 = escape(e.target.result);
                    console.log("name " + fname);
                    b64 = GetData(b64);
                    var fileobj = new XmlRpcRequest(apisite, method);        
                    fileobj.addParam({"site": sitename, "page": pagename,
                             "file":fname, "content":b64});
                    //send API request to save file
                    var response = fileobj.send();}; })(f);
                // Read in the image file as a data URL.
                reader.readAsDataURL(f);}
            else {//process image files
                var reader = new FileReader();
                // Closure to capture the file information.
                reader.onload = (function(theFile) {return function(e) {
                    // Render thumbnail.
                    var span = document.createElement('span');
                    span.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/>'].join('');
                    document.getElementById(sellist).insertBefore(span, null);
                    var fname = escape(theFile.name);
                    var b64 = escape(e.target.result);
                    console.log("name " + fname);
                    b64 = GetData(b64);
                    var fileobj = new XmlRpcRequest(apisite, method);        
                    fileobj.addParam({"site": sitename, "page": pagename,
                             "file":fname, "content":b64});
                    //send API request to save file
                    var response = fileobj.send();     }; })(f);
                // Read in the image file as a data URL.
                reader.readAsDataURL(f);
    document.getElementById(sellist).innerHTML = '<ul>' + output.join('') + '</ul>';} //end else
    } //end for loop
}
 
function handleFileDrop(evt) { //handler for drag and dropped files
    evt.stopPropagation();
    evt.preventDefault();
    var files = evt.dataTransfer.files; // FileList object.
    DoAPIFileSaveOne(evt, "droplist", files);
}
 
function handleDragOver(evt) { //drag handler
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
</script>
</body></html>

Live Demo

Fill out the form and click the "Set Key" button. This will expose a new form that where you can either browse for files on your local computer or drag and drop files into the form. This demo only works for image and PDF files.

Related Files

File nameFile typeSize
Blue%20hills.jpgJPEG image data27.85 kBInfo
Sunset.jpgJPEG image data69.52 kBInfo

Rate this Code

rating: 0+x

Discuss this Code

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License