How to get the filename and path from an upload control in xpages - xpages

I have a document that the user attaches a file to an upload control called licenseKey. In a SSJS I need to retrieve the content of that file and process it. I know that it is a ASCII text file and I know the general format. I would like to create var inStream:NotesStream for the content of the attachment, but I can't see how to do this in SSJS.
I have tried using getComponent("licenseKey") but don't see what might be next.
This code would actually be run by the user that attaches the file, so the local File Path and File Name would be valid if I could get them from the upLoad Control.
Thanks.

Julian Buss did a nice explanation
here. Quote:
How to process an uploaded file
Place code like this in the beforeRenderResponse event of an XPage to
get a handle to a just-uploaded file:
var con = facesContext.getExternalContext();
var request:com.sun.faces.context.MyHttpServletRequestWrapper = con.getRequest();
var map:java.util.Map = request.getParameterMap();
var fileDataName = "file"; //name of the POST request parameter that contains the file
var fileData:com.ibm.xsp.http.UploadedFile = map.get( fileDataName );
var tempFile:java.io.File = fileData.getServerFile();
The file is in the "xspupload" directory on the Domino Server and has
some crypting filename. You can get the original filename with
fileData.getClientFileName().
For example, you can attach the file to some Notes document with code
like this:
var correctedFile = new java.io.File( tempFile.getParentFile().getAbsolutePath() + java.io.File.separator +
fileData.getClientFileName() );
var success = tempFile.renameTo(correctedFile); //rtFiles is a rich text item on a notesdocument of your chosing
rtFiles.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT,
"", correctedFile.getAbsolutePath(), null);
correctedFile.renameTo(tempFile);
This snippet renames the temporary file to the orginal filename,
attaches it to a RichText item and renames it back to the cryptic name
(so that it will be deleted by Domino after processing).

Try this in beforerenderResponse:
var fileData:com.ibm.xsp.http.UploadedFile = facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('fileUpload1'));
if (fileData != null) {
var tempFile:java.io.File = fileData.getServerFile();
...

Related

chrome extension : how to fill input[type=file]? [duplicate]

How to append blob to input of type file?
<!-- Input of type file -->
<input type="file" name="uploadedFile" id="uploadedFile" accept="image/*"><br>
// I am getting image from webcam and converting it to a blob
function takepicture() {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 1, width, height);
var data = canvas.toDataURL('image/png');
var dataURL = canvas.toDataURL();
var blob = dataURItoBlob(dataURL);
photo.setAttribute('src', data);
}
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}
// How can I append this var blob to "uploadedFile". I want to add this on form submit
It is possible to set value of <input type="file">.
To do this you create File object from blob and new DataTransfer object:
let file = new File([data], "img.jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
let container = new DataTransfer();
Then you add file to container thus populating its 'files' property, which can be assigned to 'files' property of file input:
container.items.add(file);
fileInputElement.files = container.files;
Here is a fiddle with output, showing that file is correctly placed into input.
The file is also passed correctly to server on form submit. This works at least on Chrome 88.
If you need to pass multiple files to input you can just call container.items.add multiple times. So you can add files to input by keeping track of them separately and overwriting its 'files' property as long as this input contains only generated files (meaning not selected by user). This can be useful for image preprocessing, generating complex files from several simple ones (e.g. pdf from several images), etc.
API references:
File object
DataTransfer object
I had a similar problem with a fairly complex form in an angular app, so instead of the form I just sent the blob individually using XMLHttpRequest(). This particular "blob" was created in a WebAudioAPI context, creating an audio track in the user's browser.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'someURLForTheUpload', true); //my url had the ID of the item that the blob corresponded to
xhr.responseType = 'Blob';
xhr.setRequestHeader("x-csrf-token",csrf); //if you are doing CSRF stuff
xhr.onload = function(e) { /*irrelevant code*/ };
xhr.send(blob);
You can't change the file input but you can use a hidden input to pass data. ex.:
var hidden_elem = document.getElementById("hidden");
hidden_elem.value = blob;
I had take too much time to find how to do "url, blob to input -> preview"
so I had do a example you can check here
https://stackoverflow.com/a/70485949/6443916
https://vulieumang.github.io/vuhocjs/file2input-input2file/
image bonus

How can I convert a base64 string to image and save the file in my workspace with node Js?

After receiving a http request containing as parameter a base64 string of a photo, I want to save the file of this photo in my workspace.
I runned the code below, it works without any error, but there is no photo stored in the path mentioned.
const name = req.body.name;
var base64Str = mainImage.replace(/^data:image\/jpeg;base64,/, "");
var optionalObj = {'fileName': name, 'type':'jpeg'};
base64toimage(mainImage,path.join(__dirname,'../../static/images/${name}.jpeg'),optionalObj);
What can be the problem ?

How to save file from HTML2PDFRocket to folder on Server

My Azure Web app calls html2pdfrocket with this code:
MemoryStream stream = new MemoryStream(result.Content.ReadAsByteArrayAsync().Result);
System.IO.File.WriteAllText(path, stream.ToString());
But I get back an invalid PDF of just a few bytes. I know the URL I pass to html2pdfrocket is valid because I can paste it into their Website to test it. Do I need to async/await or something else to get all the data before attempting to save it to a folder?
No need to use async/await, the .Result does the thing like await.
A similar error in your code, stream.ToString() only converts the stream object itself to a string, but does not contain the content.
I suggest you use byte[] array instead of stream(I did test with stream, but the saved .pdf file is empty even though the content length is correct).
Try use byte[] array like below, and it works at my side:
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("apikey","xxxxx"),
new KeyValuePair<string, string>("value", "the url")
});
var result = client.PostAsync("http://api.html2pdfrocket.com/pdf", content).Result;
if (result.IsSuccessStatusCode)
{
// change the path as per your need
System.IO.File.WriteAllBytes(#"d:\temp\0618.pdf", result.Content.ReadAsByteArrayAsync().Result);
}
}

How can I transfer a file from Gmail using an app script by POSTing to a remote server

I'm using google apps scripting to write some addons to link gmail (or g suite email) to our crm system.
My current issue is trying to take a selected attachment, POST to a php script on a remote server which recreates the file (and goes from there to integrate into our crm).
Details of the code etc is below though in essence the file obviously isn't transferring correctly so something is wrong in the way the file is being received, or saved locally. The filesize is different and it won't open. So for example I select a PDF in the email which is 640k and the resulting file created on my server is over 1mb
I've setup my script with a card which includes a radio list of attachments. A button in the card attempts to post the file contents to the remote server where a receiving PHP script just saves it as a local file.
Getting attachment list to produce radio buttons:
var attachmenttosave = CardService.newSelectionInput().setType(CardService.SelectionInputType.RADIO_BUTTON).setTitle("Selected Attachment").setFieldName("attachmenttosave");
for(var i = 0; i < attachments.length; i++) {
var attachment=attachments[i];
attachmenttosave.addItem(attachment.getName(),i,false);
}
code which gets the attachment and POSTs to remote server:
var accessToken = e.messageMetadata.accessToken;
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
var messageId = e.messageMetadata.messageId;
var message = GmailApp.getMessageById(messageId);
var atc=e['formInput'].attachmenttosave;
var attachments=message.getAttachments();
var fn=attachments[parseInt(atc)].getName();
var blob=attachments[parseInt(atc)].getAs(attachments[parseInt(atc)].getContentType());
var url="https://remote.server";
var payload={"typ":"GS_SaveAttachmentToCase","email":encodeURIComponent(user),"fn":encodeURIComponent(fn), 'att':(blob)};
var options={"method":"POST","payload":payload,"followRedirects":true,"muteHttpExceptions":true};
var result=UrlFetchApp.fetch(url, options);
var data = result.getContentText();
return CardService.newActionResponseBuilder().setNotification(CardService.newNotification().setText(data).setType(CardService.NotificationType.INFO)).build();
Receiving PHP script:
`
function GS_SaveAttachmentToCase(){
$fn=urldecode($_POST['fn']);
$fp = fopen("GS/" .$fn, "w+");
fwrite($fp, (utf8_decode ($_POST['att'])));
fclose($fp);
echo "done";
}
`
ok did some more research and solved this.
get the attachment contents using
blob=attachments[parseInt(atc)].getBytes();
in the receiving php script
fwrite($fp, (base64_decode ($_POST['att'])));

Xpages get mail file from lotus

Is there a way to get the value of the mail file field from the (Company)' Directory ? I wrote a code to get the value but it is not the same in all situation.
Here is the code:
var firstChar = context.getUser().getFullName().charAt(0);
var lastWord = context.getUser().getFullName().split(" ").pop();
var str = firstChar+lastWord;
var str2 = str.slice(0, 8);
var link = "https://server/mail/";
link +=str2+".nsf/iNotes/Mail/?OpenDocument&ui=portal";
return link;
You can access the server directory as any other Notes database. Unless additional address books are there, the user should exist under their username in the "($Users)" view. From there you can retrieve the mail file and server. If it's different from the current server, you may need to check the relevant server document for the hostname.
Borrowing an example from the documentation on the NotesDirectory class and modifying for your purposes, I'd try something like:
var mynotesdir:NotesDirectory = session.getDirectory("server name");
var homeserver = mynotesdir.GetMailInfo("Joe Smith", True);
var mailFileName = homeserver[3];
var link = "https://server/mail/" + mailFileName + "/iNotes/Mail/?OpenDocument&ui=portal";
return link;
The syntax may be wrong, as I copied it from an example and modified it here instead of in Designer, but this should still serve as a good start.....

Resources