Using browseForDoc() to define file path for saveAs() in javascript - javascript

I lurk this site all the time, but I think I have exhausted my options to find the info that I need.
I just want a button to trigger acrobat to run the browseForDoc() function, take the cPath the user selects and use that as the path for the saveAs() function. It seems like it should be easier than it has been. That is a folder-level script for adobe acrobat.
I get an error of "missing ; before statement 14". Besides that, it doesn't work. Please let me know what I am doing wrong.
//get windows user name
var getLoginName = app.trustedFunction(
function(){
//Get and return the user's login name
app.beginPriv();
return identity.loginName;
app.EndPriv();
}
);
var fileExt = ".pdf";
var filePath = function(cFS, cPath, bPromptToOverwrite){
this.cFS:cFS;
this.cPath=cPath;
this.bPromptToOverwrite=bPromptToOverwrite;
}
//Open save dialog,return user input values and saveas
var mySaveDialog = app.trustedFunction(
function browse(cPath,oDoc){
app.beginPriv();
app.browseForDoc(){bSave: true, cFilenameInit: oDoc, cFSInit: ""};
return this.cPath;
var myPath = new filePath{cPath: browse.cPath};
this.saveAs(myPath,myFile+fileExt);
app.endPriv();
}
);

Related

File attachment is not opening-Not Allowed Error

This is my first attempt to prepare a dynamic pdf form in livecycle designer es4. In this form, there is an option to add and view attachment. As I have little experience in javascript coding, I went to the adobe forum and found a very good example here. I have done some changes in original code to run in my form. I can attach file successfully with this code. But my problem is that when I want to open file attachment in Acrobat Pro XI, it is showing below error instead of opening the file. This error is showing independent of file attachment type (e.g. .doc, .jpg, .txt and .pdf file).error image. Here is screenshot of security of Acrobat Pro XIscreenshot 1 screenshot 2 and file linkhere.
Below code is written in the form-
//Code for add button
// Get Import Name
var cName = AttachName.rawValue;
// Test for empty value
if(!/^\s*$/.test(cName))
{// Do Import
try{
var bRtn = event.target.importDataObject(cName);
if(bRtn)
{
var cDesc = AttachDesc.rawValue;
if(!/^\s*$/.test(cName))
{
var oAtt = event.target.getDataObject(cName);
oAtt.description = cDesc;
}
app.alert("File Attachment Successfully Imported",3);
}
else
app.alert("Unable to import File Attachment",0);
}catch(e){
app.alert("An Error Occured while Importing the File Attachment:\n\n" + e);
}
}
else
app.alert("Attachment name must be non-empty");
//code for populating dropdown list
this.rawValue = null;
this.clearItems();
var a = event.target.dataObjects;
if (a !== null) {
for (var i = 0; i < a.length; i++) {
this.addItem(a[i].name);
}
}
//code for open attachment button
var cName = AttachNameSel.rawValue;
//var nAction = ExportAction.rawValue;
try{
event.target.exportDataObject({cName:cName, nLaunch:2});
} catch(e) {
app.alert("An Error Occured while Exporting the File Attachment: " + cName + "\n\n" + e);
}
Any help from anyone in the community would be greatly appreciated.
Thanks
Tony

Using CKEditor custom filebrowser and upload with ASP.Net MVC

I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.
<script type="text/javascript">
$(document).ready(function () {
$(".returnImage").click("click", function (e) {
var urlImage = $(this).attr("data-url");
window.opener.updateValue("cke_72_textInput", urlImage);
window.close();
});
});
</script>
In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.
Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?
On view:
$(document).ready(function () {
CKEDITOR.replace('Text-area-name', {
filebrowserImageUploadUrl: '/Controller-name/UploadImage'
});
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
config.language = 'de';
// config.extraPlugins = 'my_own_plugin'; // if you have any plugin
// config.uiColor = '#AADC6E';
// config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 );
// config.contentsLanguage = 'de';
config.height = 350; // 350px, specify if you want a larger height of the editor
config.linkShowAdvancedTab = false;
config.linkShowTargetTab = false;
};
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;
if (dialogName == 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('advanced');
}
if (dialogName == 'image') {
dialogDefinition.removeContents('Link');
dialogDefinition.removeContents('advanced');
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('txtBorder');
infoTab.remove('txtHSpace');
infoTab.remove('txtVSpace');
infoTab.remove('cmbAlign');
}
});
}
On Contoller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
{
if (file.ContentLength <= 0)
return null;
// here logic to upload image
// and get file path of the image
const string uploadFolder = "Assets/img/";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
file.SaveAs(path);
var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
uploadFolder, fileName);
// passing message success/failure
const string message = "Image was saved correctly";
// since it is an ajax request it requires this string
var output = string.Format(
"<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
CKEditorFuncNum, url, message);
return Content(output);
}
I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.
Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
{
/*
add logic to upload and save image here
*/
var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
var url = string.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Url.Content(path)); // URL path to uploaded image
var message = "Saved!"; // Optional
var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>",
CKEditorFuncNum,
url,
message);
return Content(output);
}

How to display image stored in variable using the url?

USING PARSE.COM AND THE JAVASCRIPT SDK
With the below code I can get as far as letting the user upload an image from the webpage and storing that as an object in a "file" column in the parse db.
I can store the image details, including the url in the
What i'm unable to do is extract the url back out and display the image on a html page.
I've added the screen shots to show how the data is held in var profilePhoto but i'm then unable to make it show on the page using $("profile_pic").attr('src',jobApplication[0]);
What have I overlooked ? I've searched SO and cannot find an relevant question that helps with this.
RESULTS IN INSPECT ELEMENT
Arguments[1]0: t.Filecallee: function () {length: 1__proto__: Object user_profile.html:408
t.File {_name: "tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg", _source:
t.Promise, _previousSave: t.Promise, _url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc…fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg",
name: function…}_name:
"tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"_previousSave:
t.Promise_source: t.Promise_url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc-36390888e497/tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"proto:
Object
CODE
$(document).ready(function() {
var parseAPPID = "XXX";
var parseJSID = "XXXX";
//Initialize Parse
Parse.initialize(parseAPPID,parseJSID);
$("#fileUploadBtn").on("click", function(e) {
var fileUploadControl = $("#fileUploader")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = file.name;
console.log("here goes nothing...");
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
console.log("Woot!");
console.dir(arguments);
var User = Parse.Object.extend("_User")
var jobApplication = Parse.User.current();
jobApplication.set("ProfilePic", parseFile);
jobApplication.save();
var profilePhoto = jobApplication.get("ProfilePic");
console.log(profilePhoto);
$("profile_pic").attr('src',jobApplication[0]);
}, function(error) {
console.log("Error");
console.dir(error);
});
}
});
});
$("profile_pic") returns elements with profile_pic tag name, which obviously is not the thing you need. Don't see your HTML, but if profile_pic is id or class name of your img element, this will work if you type $("#profile_pic") or $(".profile_pic") respectively.

How to change a file name and download it when a button is clicked using JavaScript

I have one download button created in JavaScript that links to particular file.
var strDownloadButton = "<br/><INPUT type="button" value="Download" onclick="add()"/>"
window.location.href = "/images/image1.jpg";
I have to rename the file image1 to image2 before downloading, so I use:
<a href="/images/image1.jpg" download="image2" >Download</a>
The problem is that there are 2 download buttons created (HTML5 download attribute created 1 more).
Is there any way to use the same button created by JavaScript, and refer into download attribute?
I have no idea what are you doing Brad Christie,
<a id="download" href="Chrysanthemum.jpg" download="image2" >Download</a>
document.getElementById("download").setAttribute("download", "image3")
here, you have an element that you want to download, you get the element and change its download attribute.
I'm not 100% sure it'll work, but I've done something like this before to download a resource and rename it using javascript. It does, however, mean the resource has to be on the same domain as the page otherwise you will run into a cross-domain security issue. Also, please excuse the fact that I'm using jQuery, but if you need to go without I'll let you look up how to make a cross-browser AJAX call.
With that said:
<!-- your anchor decorated with data-saveas -->
Download
<!-- wiring it up using jQuery/AJAX/Blob -->
<script type="text/javascript">
// Helper to convert AJAX response in to a BLOB
function dataToBlob(data, mimeString){
// convert data to ArrayBuffer
var buffer = new Int8Array(new ArrayBuffer(data.length));
for (var i = 0; i < data.length; i++){
buffer[i] = data.charCodeAt(i) & 0xff;
}
// http://stackoverflow.com/a/15302872/298053
try {
return new Blob([buffer],{type:mimeString});
} catch (e1) {
try {
var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder){
bb = new BlobBuilder();
bb.append([buffer.buffer]);
return bb.getBlob(mimeString);
} else if (e.name == 'InvalidStateError'){
return new Blob([buffer.buffer],{type:mimeString});
}
} catch (e2) {
}
}
return null;
}
// iterate over all the items that are marked as saveas
$('a[data-saveas]').each(function(){
var $this = $(this);
// Get the actual path and the destined name
var target = $this.prop('href'),
saveas = $this.data('saveas');
// make an ajax call to retrieve the resource
$.ajax({
url: target,
type: 'GET',
mimeType: 'text/plain; charset=x-user-defined'
}).done(function(data, textStatus, jqXHR){
var mimeString = jqXHR.getResponseHeader('Content-Type'),
blob = dataToBlob(data, mimeString);
if (blob){
// now modfy the anchor to use the blob instead of the default href
var filename = saveas,
href = (window.webkitURL || window.URL).createObjectURL(blob);
$this.prop({
'download': saveas,
'href': href,
'draggable': true
}).data({
'downloadurl': [mimeString, filename, href].join(':')
});
}
});
});
</script>
Not tested, but should work. Basically, you can go fetch the resource using jQuery and store it in to a blob with an assigned name. If it's able to do so, the link now becomes a custom-named blob resource with the provided name. if it can't the default functionality is retained and the user needs to name it his/herself.

Response Email Activity Images in CRM 2011

How can I preserve images in a response to an email activity?
The images in the email show when viewed in CRM - they are added as attachments. When I click the 'respond' button, write a response, and send the response the images are stripped from the email and are not attached to the email.
I have been trying all sorts of things with JScript .
I would rather not have to write anything other than JScript.
This is possible with javascript. I don't know what you tried but this can be done. I.e. catch the send event of your form and create the attachment with Javascript.
Other options are:
You could use a workflow to attach the note of the parent email to
the response. But then you will be forced to save your email wait a
little while (execution of the workflow) and then send the email.
Write plug-in code (but you won't use anything else but Javascript
Javascript to delete attachment:
function deleteAttachments(){
var notesId = {GUID of notes};
var objNotes = new Object();
objNotes.DocumentBody = null;
objNotes.FileName = null;
objNotes.FileSize = null;
objNotes.IsDocument = false;
updateRecord(notesId, objNotes, “AnnotationSet”);
}
function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var updateRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid’” + id + “‘)”, false);
updateRecordReq.setRequestHeader(“Accept”, “application/json”);
updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8″);
updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE”);
updateRecordReq.send(jsonEntity);
}
I can access the attachments here: https:{org. URL}/xrmServices/2011/OrganizationData.svc/EmailSet(guid'3848cb4d-673f-e211-b9af-005056bd0001')/email_activity_mime_attachment
guid is the guid of the email.
The image is stored in d:Body as Base64.
Now all I need to do is rewrite img for each inline image with src="data:image/png;base64,theverylongstring...
All inline images will be preserved in the response as Base64.

Categories

Resources