Here is an example how to upload a file with Ajax to a XPage. It is a simple Javascript, and adds the required fields to the xhr request. This example works in FireFox and Chrome and should work on Domino >=8.5.2.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.data>
<xp:dominoDocument
var="document1"
formName="RTItem"
action="editDocument"
concurrencyMode="force">
</xp:dominoDocument>
</xp:this.data>
<xp:fileUpload onchange="handleFiles(this.files)"
id="fileUpload1"
value="#{document1.Body}">
</xp:fileUpload>
<xp:eventHandler event="onsaveDoc" submit="false" refreshMode="norefresh" immediate="false" save="true" id="saveDoc" />
<xp:button
value="ajaxSave"
id="buttonAjax">
<xp:eventHandler
event="onclick"
submit="false">
<xp:this.script><![CDATA[sendFiles();]]></xp:this.script>
</xp:eventHandler>
</xp:button>
<xp:div id="fileData" />
<xp:scriptBlock id="scriptBlockAjax">
<xp:this.value>
<![CDATA[
function handleFiles(files) {
var i = 0;
var dataDiv = dojo.byId('#{id:fileData}');
var fileList = files;
for(i = 0; i < fileList.length; i++)
{
var img = document.createElement("img");
img.file = fileList[i];
img.name = 'no_'+ i;
img.classList.add("fileData");
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(fileList[i]);
dataDiv.appendChild(img);
}
}
function FileUpload(img, file) {
var xhr = new XMLHttpRequest();
this.xhr = xhr;
var frm = new FormData;
frm.append( "#{id:fileUpload1}", file);
frm.append( "$$viewid", dojo.byId('view:_id1__VUID').value);
frm.append( "$$xspsubmitid", "#{id:saveDoc}");
frm.append( "view:_id1", "view:_id1");
xhr.open("POST", "#{javascript:facesContext.getExternalContext().getRequest().getRequestURI()}", true);
xhr.send(frm);
}
function sendFiles(){
var files = document.querySelectorAll(".fileData");
for(var i = 0; i < files.length; i++)
{
new FileUpload(files[i], files[i].file);
}
}
]]>
</xp:this.value>
</xp:scriptBlock>
</xp:view>
The fileupload control executes the javascript method handleFiles when a new file is selected. This method „converts“ the file to a DOM image and attaches it to the DIV fileData.
When clicking the button ajaxSend, the sendFiles method is fired and sends all selected files with xhr Requests to the server. The value of the $$submitid identifies a server side event which saves the document with the received attachment as new document.
Keep in mind: There is NO full refresh.
If you selecting some file in the browser…
.. and click on „ajaxSave„, the files are posted to the server:
The server side event saves the uploaded files to new documents:
Pingback: A Drag&Drop file upload custom control - XpageXplorer