Access component variable in Callback function Salesforce Lightning component

You might have face issue somewhere in component where you are triggering some JavaScript callback function, and in callback function you want to perform some logic on component variable but you got stuck in accessing component.

Becuase modifiing component outside the normal rerending lifecycle is not allowed. 

for example you using setTimeout().

To resolve this issue wrap your callback function into $A.getCallback(), which modifies a component outside the normal rerendering lifecycle.


window.setTimeout(
    $A.getCallback(function() {
        component.set("v.attribute", "attributevalue");
    })
);

 

Hope this will help! Enjoy Coding!!!

For more information visit here.

Application and Component in Salesforce lightning

 This blog will be focusing on two event types provide by Salesforce. One is Application Events and another is component Events and how we can pass values from one component to another.

Application Events

When you want to pass values between two independent component at that time we will use Application Events. Lets say you have two independent, say SENDER component which takes Name as input from the user and passes its value to say RECEIVER component.

Steps to create Application Event:

1. Create a Event with type as APPLICATION 

<aura:event type="APPLICATION" description="Description for Event">
          <aura:attribute name="param" type="Object" description="Description for parameter"/>
      </aura:event>

2. Register event in SENDER component

<aura:registerEvent name="senderEvent" type="c:EventName">
<aura:attribute type="String" name="firstname" />
<lightning:input type="text" name="firstname" value="{!v.firstname}" />
<button onclick="{!c.callEvent">Send</button>

JS controller 
({
     callEvent : function(cmp, event, helper) {
        var e = $A.get("e.c:EventName");  // get Event 
        e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
        e,fire();  // fire event

    }
})

3. Now Handle event in RECEIVER component by adding handler for event
<aura:handler event="c:EventName" action="{!c.receiveParam}" /> //hadler to handler event
JS controller
({
    receiveParam : function(cmp, event, helper) {
        var param = event.getParam("param"); //get param value 
        console.log("Value recieved from SENDER component is: " + param);
    }
})

Every component which has Handler can receive param value send by SENDER component for APPLICATION type event.

Component Event

Lets say you want pass value between child to parent in this case you can use component event. Here sender will be child component and reciever will be parent component.

Steps for it.

1. Create event of type COMPONENT

<aura:event type="COMPONENT" description="Description for Event">
          <aura:attribute name="param" type="Object" description="Description for parameter"/>
      </aura:event>

2. Register event in SENDER component same as in Step 2 of Application Event
    attribute name for aura:registerEvent should be same in aura:handler name attribute.

here: name="senderEvent"

<aura:registerEvent name="senderEvent" type="c:EventName"> 
<aura:attribute type="String" name="firstname" />  
<lightning:input type="text" name="firstname" value="{!v.firstname}" /> 
<button onclick="{!c.callEvent">Send</button>

JS controller 
({
     callEvent : function(cmp, event, helper) {
        var e = $A.get("e.c:EventName");  // get Event 
        e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
        e,fire();  // fire event

    }
})

 

3. Add handler with name="senderEvent" 

<aura:handler name="senderEvent" event="c:EventName" action="{!c.receiveParam}" />
//handler to handle event

 

It's mandatory in Component event to set name attribute in event registration and handler, as param can be exchange in parent child component only.


Hope you like the post! Enjoy Coding.

Page border on cover page visualforce as word document

Hello folks,

In this blog I am going to give example to how to apply border on cover page of visualforce page word document.

To load visualforce page as word document you need to add attribute ContentType="application/msword#name_of_Document.doc". you can replace name_of_document with file name you want to add.

lets jump on code snippet to add page border.Below style sheet will add page border on cover page.



          @page Section1 {
                size: 8.5in 11in;
                margin: 0in 1in 0.5in 1in;
                mso-header-margin: 0.5in;
                mso-header: h1;
                mso-footer: f1;
                mso-footer-margin: 0.5in;
                mso-paper-source: 0;
                mso-page-border-display: first-page;
                font-family: Calibri; 
                mso-border-alt: solid black 2pt;
                mso-page-border-offset-from: edge;
                padding: 20px 20px;
         }



      mso-border-alt: solid black 2pt;
      mso-page-border-offset-from: edge;


Above line will add border to page and adding padding to section will add padding to page border.

Hope this will help, Please comment your question or suggestions.




Drag and drop sorting in visualforce page using angularJs


Hello folks,

In this blog I am going to give example to apply drag-drop sorting in visualforce page with use of angularJs.

Lets start with creatting basic Html template to host our app. We will use the ng-app and ng-controller directives to link up the body tag to our Angular application. At the bottom we will include our required libraries.


Prerequisite:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/0.15.0/sortable.min.js"></script>


In this code we define an Angular module and name it ngApp, and include the ui.sortable in the requires parameter. This ui.sortable is what wires up angular-ui-sortable to our module. We also define the controller called myController for our module and inject the Angular $scope object. This is where we will set up our Angular sortable.


<script >
      var ngApp = angular.module('myNgApp', ['ui.sortable']);
      ngApp.controller('myController', function ($scope) {

           $scope.names = [ "Test1", "Test2", "Test3" ];

      });


</script>
Now lets use this $scope name variable to display data in Ul by adding ng-model Directive on it and ng-repeat to loop over array.  To make this list sortable, all we need to do is use the ui-sortable directive.
<ul ui-sortable="sortableOptions" ng-model="names">
      <li ng-repeat="person in people" class="list-group-item">{{name}}</li>
</ul>
To see this in action let’s add a pre element and bind it to the people array that will show the order of array in real time.
<pre>{{names}}</pre>

Final code will look like below.
<apex:page standardStylesheets="false" sidebar="false" showHeader="false">
    <apex:slds />
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">
     </script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/
jquery-ui.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/
angular.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/
0.15.0/sortable.min.js"></script>
    <script>
          var ngApp = angular.module('ngApp', ['ui.sortable']);
          ngApp.controller('myController', function ($scope) {
    
               $scope.names = [ "Test1", "Test2", "Test3" ];
    
          });
    </script>
    <body ng-app="ngApp" ng-controller="myController">
        <article class="slds-card">
            <div class="slds-card__header slds-grid">
                <div class="slds-media__body">
                    <h2 class="slds-card__header-title">
                      <a href="javascript:void(0);" 
class="slds-card__header-link slds-truncate" title="Names">
                        <span>Name List</span>
                      </a>
                    </h2>
                </div>
                
            </div>
            <div class="slds-card__body slds-card__body_inner">
                <ul ui-sortable="sortableOptions" ng-model="names" 
class="slds-has-dividers_top-space">
                    <li ng-repeat="name in names " class="slds-item">{{name}}</li>
                </ul>
                <pre>{{names}}</pre>
            </div>
        </article>
    </body>
    
</apex:page>

Output:




Hope it will help. Let me know your comments.

Go to specific Page number in DataTable Jquery


You want to go to specific page number using Jquery in DataTable Pagination then you can use below to apply.

1. Go to specific page number

    $(document.getElementById('idofTable').DataTable().table.fnPageChange( pagenumber );

2. Destroy DataTable
 
     var table = $(document.getElementById('idofTable').DataTable();
     table.fnDestroy();


That's all in this post.
Hope this helps..

Happy Coding..!!!!!!

Create CSV file using Jquery/ JavaScript


Below is sample Html and Jquery to create CSV using Jquery or Javascript.

if have issue in generating data containing comma (,) use below code.


<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>

<input type="button" value="select table" onclick="
createCSVFile(document.getElementById('tableId') );">
<script> function createCSVFile(tablehtml) { export_table_to_csv(tablehtml,'report.csv'); } function download_csv(csv, filename) { var csvFile; var downloadLink; // CSV FILE csvFile = new Blob([csv], {type: "text/csv"}); // Download link downloadLink = document.createElement("a"); // File name downloadLink.download = filename; // We have to create a link to the file downloadLink.href = window.URL.createObjectURL(csvFile); // Make sure that the link is not displayed downloadLink.style.display = "none"; // Add the link to your DOM document.body.appendChild(downloadLink); // Lanzamos downloadLink.click(); } function export_table_to_csv(html, filename) { var csv = []; var doc = document.implementation.createHTMLDocument("New Document"); var p = doc.createElement("p"); p.innerHTML = html; doc.body.appendChild(p); var rows = doc.querySelectorAll("table tr"); for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll("td, th"); for (var j = 0; j < cols.length; j++) { //check if data contains comma if(cols[j].innerText.trim().includes(',')){ row.push('"'+cols[j].innerText.trim() +'"'); } else{ row.push(cols[j].innerText.trim()); } } csv.push(row.join(",")); } // Download CSV download_csv(csv.join("\n"), filename); } </script>
Thanks for visiting.

If have any doubt or suggestions please comment.

Have happy coding. :) !!!!!!!

Copy to Clipboard using JavaScript.

Below is the easiest way to use JavaScript to copy element to Clipboard.



<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>



<input type="button" value="select table"

   onclick="copyElementContents( document.getElementById('tableId') );">


<script>

    function copyElementContents() {

            var el = $('*[id*=pbt]')[0]; // element to be copied to clipborad

            var body = document.body, range, sel;

            if (document.createRange && window.getSelection) {

                range = document.createRange();

                sel = window.getSelection();

                sel.removeAllRanges();

                try {

                    range.selectNodeContents(el);

                    sel.addRange(range);

                } catch (e) {

                    range.selectNode(el);

                    sel.addRange(range);

                }

                document.execCommand("copy");

                sel.removeAllRanges();

            } else if (body.createTextRange) {

                range = body.createTextRange();

                range.moveToElementText(el);

                range.select();

                range.execCommand("copy");

               

            }

        }

</script>
Enjoy Coding .

If have any doubt please comment.

Thanks.

Simple Loader image for Visualforce Page.

Hello guys,

I am gonna show you simple way to pop up loader image i.e status image for loading purpose using CSS and javascript function.

Using simple html div and Javascript you can create your status loader.

Below i am gonna show you simple html tag for it. you can call javascript function on onclick method to show loader and hide it on oncomplete.

ADD BELOW STYLE TO YOUR VF PAGE

#filter{ 
      display:none;
      background-image: url({!URLFOR($Resource.Static_Resource_Main,'Static_Resource_Main/loading32.gif')});
      z-index:10000;
      position:fixed;
      top:0%;left:0%;
      width:100%;
      height:100%;
      background-repeat:no-repeat;
      background-position:center;
      background-color: #ffffff;
      opacity:0.6;
      filter:alpha(opacity=50);
} 
Call startProces method when you call action( Controller function or any function after which you want to show loading image).

 

function startProcess()
{
      $('#filter').show();
}

function endProcess ()
{
      $('#filter').hide();
}   
Add below Div tag at the start of body tag or form.

<center>
    <div id="filter"></div>
</center>                        
startProcess will add display: block css to div.
endProcess  will hide the div.

Its just awsomeness of css.

Hope you will like it.
Enjoy coding....

How to know how many records where sucess and failed in batch class?

Lets say you want to send an email to some user on end of batch class that how many records where successfully executed and how many were failed to be executing.

Its very simply to do if you know the Object used to store data related to Async jobs.

There is called Standard object named AsyncApexJob which store information of jobs runs.

You can query on AsyncApexJob object to get record of currently run batch by its Batch id in finish method.

Fields to be Used:

JobItemsProcessed: Number of job items processed. Label is Batches Processed.
NumberOfErrors: Total number of batches with a failure. A batch is considered transactional, so any unhandled exceptions constitute an entire failure of the batch. Label is Failures.


global void finish(Database.BatchableContext BC) {
 
 
//Below code will fetch the job Id

 AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];             

}
                            
you can use above code to send mail with details of job.

Hope you will find it useful.

For more details of Object visit:
Here

Custom button: How to pass currency field to an Apex web service?


you can try using the VALUE function to get the decimal value from the currency field before passing it to the webservice method.
Example:
We want to pass decimal value of Opportunity Amount. Then we use below code in custom button to pass decimal value to web-service.
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}

var amt = {!VALUE(TEXT(Opportunity.Amount))};
var retVal = sforce.apex.execute("WSclassname", "WSmethod", {oppAmt:amt});
alert (retVal) ;
window.location.reload() ;

Share certain records with only certain users


If you would require to have some records to only be shared with certain users, e.g. based on record level, to a certain group (those selected users), and the rest of the records (e.g. records that are the other recod types) with the rest of the internal users.

It can be done by restricting all objects on OWD(Organization-Wide Defaults) level to private and then share certain records.By default 'Grant Access Using Hierarchies' is selected (checked). If you don't want to share the records with users based on role hierarchy, make sure to uncheck this box for respective objects in OWD settings.

Once the OWD setting for an object is set to Private, applying Sharing rules based on criteria would be the best way to meet your requirement scope.If you want Users to share at record level, you can also enable Manual Sharing.

You can navigate to OWD by searching Sharing settings in Setup > quick search.

You can refer Below link for more sharing Information.
https://developer.salesforce.com/docs/atlas.en-us.securityImplGuide.meta/securityImplGuide/security_data_access.htm

Reset changed user profile permissions

Hi,

There is no way to "Reset" the changes made on your profile.

But there is one way by which you can revert it some what.

you can

look in to the "View Setup Audit Trail" from Setup and see the list of changes made to your profile, and then try to correct it manually.


Hope this helps.

Merge field syntax is correct yet the generated PDF document is not displaying the data : Steelbrick CPQ


This might be because of merge field is not populated on source code. So try to verify your merge field in source code.

If your merge field syntax is correct yet the generated PDF document is not displaying the data or is displaying an error, click the HTML button highlighted below in your template content toolbar to troubleshoot.

Ensure your merge field name was pasted in correctly. Formatting tags can get inserted within the brackets when pasted in from a rich text applications.
Instead, paste from Notepad, which strips out all excess formatting.

Alternatively, click the HTML button on the template content editing toolbar and remove formatting tags manually, making sure that the merge field syntax is not interrupted by these tags.

If still not working click Source Button and check if merge field is populated.


For merge field information visit: https://community.steelbrick.com/t5/Quote-Templates-Knowledge-Base/Merge-Fields/ta-p/299

Custom Picklist lookup using javascript in Visual page

In this post I'm gonna show you how to create simple custom picklist lookup in Visual page using javascript.

We will use window eventlistner to get data from child window open by parent window.

Here is snippet of my simple vf page.

  
<apex:page >
    <script>
        function open_pop_up(idx, field, sObj){
            var child = window.open('/apex/picklistLookup?idx='+idx+'&field='+field+
'&sObj='+sObj+'', '_blank', 
'toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400')
            console.log('==> Child: ' + child);
        }
        
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
        //Listen to message from child window
        eventer(messageEvent,function(e) {
            console.log('parent received message!: ',e.data);
            var dataArr = e.data.split(':'); 
            var elmtId = e.data.substring(0, e.data.lastIndexOf(':'));
            var datavalue = e.data.substring(e.data.lastIndexOf(':') + 1,e.data.length);
            document.getElementById(elmtId).value = datavalue;
        },false);  
        
    </script>
    
    <input id="testId" value="" onclick="open_pop_up('testId','CustomerPriority__c',
'Account');"/>
</apex:page>

Let me explain the code.

when we click on input it will open popup lookup window.
Here i have use my custom picklist field CustomerPriority__c of Account Object for test data.

Now new vf page for lookup popup window.

  
<apex:page controller="PicklistLookupCon" showHeader="false">

    <apex:variable value="{!0}" var="rowNum"/>
    
    <table>
        <tr>  
            <td></td>  
            <td>
                <input type="button" value="Insert Selected" onclick="InsertSelected()" class="btn"/>
            </td>
        </tr>
        <apex:repeat value="{!picklistValues}" var="plv">
            <tr>
                <td>
                    <input type="checkbox" onclick="selectValue('{!rowNum}', this.checked, '{!plv}')"/>
                </td>
                <td>{!plv}</td>
            </tr>
            <apex:variable value="{!rowNum+1}" var="rowNum"/>             
        </apex:repeat>            
    </table>
    
    <script type="text/javascript">
        var arrValue  = new Array();
               
        function selectValue(id, isChecked, value){

            if(isChecked == true){
                arrValue[arrValue.length] = value;
            }else{
                var index = arrValue.indexOf(value);
                arrValue.splice(index,1);
           }  
        }
           
        function InsertSelected(){
            console.log(window.parent.opener);
            var win = window.parent.opener;
            var dataStr= '';
            
            for(var k=0;k<arrValue.length;k++){
                if(k==0) dataStr = arrValue[k];
                else dataStr +=','+arrValue[k];
            }
            win.postMessage('{!$CurrentPage.parameters.idx}:'+dataStr, window.parent.opener.location.href); 
            window.parent.close();
        }
  </script> 
</apex:page>

controller:

public without sharing class PicklistLookupCon {

    string sObj = Apexpages.currentpage().getParameters().get('sObj');
    string field = Apexpages.currentpage().getParameters().get('field');

    public picklistLookupCon(){
    
    }
        
    public List picklistValues{
      get{
          if(picklistValues!=null)
              return picklistValues;
          else{
              picklistValues = new List();
              
              Map gd = Schema.getGlobalDescribe(); 
              Schema.SObjectType ctype = gd.get(sObj);
              Map fmap = ctype.getDescribe().fields.getMap();
              Schema.DescribeFieldResult fieldResult = fmap.get(field).getDescribe();
              List ple = fieldResult.getPicklistValues();   
              
              for( Schema.PicklistEntry f : ple){
                  picklistValues.add(f.getValue());
             }
          }
          return picklistValues;
      }
      set;
    }
    
 }

That's it.

Yepppieee you done it.

Simple Alexa skill in Node.js using Heroku as hosting server

The think which we gonna need is;
1. Heroku login
2. Git respository
3. Amazon developer account

We will use command promt for developing node js code and deploying it to heroku.

Here are the links for download CLI for heroku and gitHub/
GitHub: https://git-scm.com/download/
Heroku cli: https://devcenter.heroku.com/articles/heroku-cli

First of all create a new directory in local machine name it whatever you like, i have given name sample. Similar create a new repository in your git account.you will below screen:




Go through the given step for creating a new respository on the command line

for using alexa we will use alexa-app-server library.

for using node js you will need node js to be install so first install npm to your local machine.
https://nodejs.org/en/download/

For installing alexa-app-server type:

npm install alexa-app-server

after finishing installing alexa-app-server lib, Create a file server.js and copy paste below code in it.

'use strict';

var AlexaServer = require( 'alexa-app-server' );

var server = new AlexaServer( {
 httpsEnabled: false,
 port: process.env.PORT || 80
} );

server.start();

Let me explain what does code means.

Here we have set port to be used by server. if code is running from heroku than it will use  port given by heroku by (process.env.PORT) other wise port 80 will be use.

Now we will create Procfile. this will tell heroku what to do when process will run.file name should be without extension. just use Procfile.

web: node server.js

Now will create Package.json file by tying npm init
this will ask some question and after completing that json file will get created.

After that push your file to git by performing below command.

git add .
git commit -m "added procfile and server.js"
git push origin master

Now, create new folder in main folder named apps and in that create sub folder skills  where add file for our skills.create new Github repository for skills name it whatever you like i use sampleskills.
perform similar step of initiaze repo and do the initial commit/push.Now we will indicate github that apps/skills is submodule. To do this go to main folder and type

git submodule add https://github.com/rsanjuseason/sampleskills.git apps/skills

Replace https://github.com/rsanjuseason/sampleskills.git with your skill git link.

Now we will generate package.json for skills folder.so that npm can know that it submodule.
To do this run below command:

npm init

Now we will install alexa-app package.

npm install alexa-app

Now again regenerate package.json for install dependency.

Now it's time to create index.js file for performing something by skill, something like say hello world.

module.change_code = 1;
'use strict';

var alexa = require( 'alexa-app' );
var app = new alexa.app( 'myskill' );


app.launch( function( request, response ) {
        response.say( 'Welcome to Alexa World' ).reprompt( 'Ask Something.' ).shouldEndSession( false );
} );


app.error = function( exception, request, response ) {
 response.say( 'Sorry some error occured ' + error.message);
};

app.intent('sayHello',
  {
 "utterances":[ 
  "say Hello",
  "Hello alexa",
  "What's up",
  "Hey alexa"]
  },
  function(request,response) {
    response.say("Hello, Welcome to alexa world.");
  }
);

module.exports = app;


To test our code run below command in cmd from main folder:

node server.js

Then, open browser and open below link:

localhost/alexa/myskill



Hope this works, then we will deploy it heroku so, that it can invoke from any place.

So, now we will commit our work to git.
first commit/push skill files to git.move to skill directory and type:

git add .
git commit -m "skills file index.js"
git push origin master


then we will push out main folder files to git by below commands after moving to main directory:

git submodule forech git pull origin master
git add .
git commit -m "update submodule"
git push origin master

Now create New app in heroku to deploy our files.Mine is helloworldskill

after creating app type below command

heroku login

After this you have enter your login details then,

heroku git:remote -a helloworldskill

Replace helloworldskill  with your app name.then push your file.

git push heroku master


Now its time create skill on amazon.go to your developer amazon and create a new skill



Add intent schema and utterences.


In configuration tab select Https and below url 

https://helloworldskill.herokuapp.com/alexa/myskill

Replace https://helloworldskill.herokuapp.com with your heroku app url.



In SSL Certificate select

My development endpoint is a sub-domain of a domain that has a wildcard certificate from a certificate authority

Now its time test our skill, enter utterance it should work fine.



You can test it in simulator or echo dot.
Here is link for simulator

https://echosim.io

Just Say

"alexa, Ask helloworld to say hello"

it will repeat back with

"Hello, welcome to alexa world"

Yehhhh, we have created our first alexa skill.

Hope this helps
Thanks.







Simple Status Loader with simple Html salesforce

A simple status loader image can be easily done using simple html div tag.

Here is code snippet for it.

<div id="loading" style="display:none;">
  <div style="width: 100%; height:100%; background:#000; opacity: 0.4; top:0px; left:0px; 
      position: fixed; z-index:1000000;"></div>
     <div class="dv_load" style="position:fixed;top:40%;left:50%;z-index:1000000">
        <img src="/img/loading24.gif" style="vertical-align:middle;" />
        <span>Loading...</span>
      </div>
</div>

you can load is just by changing its display property that is display:none to block.

function startProcess() {
   document.getElementById("loading").style.display = 'block';
}
    
function endProcess() {
    document.getElementById("loading").style.display = 'none';
}

function startprocess for loading image and stopprocess for stop i.e to hide.

If have any questions, you can as in comment.

Thanks.
Have happy coding.



Auto generate password apex salesforce.

To generate random password you can use crypto class for generating password in apex.

crypto class will generate random blob. Use can use that blob for creating String.
use trim string to whatever length.

Here is Sample class for generating password:

public class PasswordGenerator {
public static String getPassword(Integer passlength) {
Blob blobKey = crypto.generateAesKey(128); String key = EncodingUtil.convertToHex(blobKey); System.debug(key);
return key.substring(0,passlength); } }

How to put a static image in a flow designer ?


The Rich text editor on the screen element currently does not support img src tags.
However, the flow run-time interprets any text as HTML. So, you could store the html markup in a custom setting or any database record, fetch it in a variable and use that in the screen.

You can display document image in flow Designer by creating text variable.


Create Variable of type text in flow Designer.

Data Type: text
Input/output type :  Output only
Default value:   
<img src="https://Domain_url/servlet/servlet.FileDownload?file=Your_documentid&oid=Org_id" width="100px" Height="100px"/>

Note: Domain_url  >>>  set your domain url
           Your_documentid >> set your document id.
          Org_id >>> set your org id

You can get your Org id by Navigate to Administration Setup > Company Setup> Company Information.

you will find org id at Salesforce.com Organization ID field.

Now use this newly created variable in Screen.

Resize an image before upload using JQuery.



function handlePhoto(evt)
{
var file = evt.target.files[0];
var FR = new FileReader();           
var img = new Image();
var can = document.createElement("canvas");
var ctx = can.getContext('2d');
FR.onload = function(e) {
img.src = = e.target.result;
img.onload = function() {      
var ctx = can.getContext('2d');
//Set canvas 
var max_size = 750,// pull max size from a site config
width = this.width,
height = this.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
can.width = width;
can.height = height;
ctx.drawImage(this, 0, 0,width,height);
var dataURI = can.toDataURL(); 
dataURI = dataURI.replace(/^data:image\/(png|jpg);base64,/, "");
        console.log('New Image source: ' + dataURI);                         
}
};       
FR.readAsDataURL( this.files[0] );
}

Http Request with multipart/form-data Salesforce upload file.



public void upload(String boundary,string filename,boolean file_body) {


    String header = '--' + boundary + '\r\n' +
                        + 'Content-Type: application/octet-stream\r\n'+
                        + 'Content-Disposition: form-data; name="file";filename="' + filename +'"';

        String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header + '\r\n\r\n'));

        String footer = '--' + boundary + '--';

        while(headerEncoded.endsWith('='))
        {
            header += ' ';
            headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
        }

        String bodyEncoded = EncodingUtil.base64Encode(file_body);
       
        Blob bodyBlob = null;

        String last4Bytes = fileContent.substring(bodyEncoded.length()-4,bodyEncoded.length());
        System.debug('----->last4Bytes: '  + last4Bytes );

        if(last4Bytes.endsWith('==')) {
            last4Bytes = last4Bytes.substring(0,2) + '0K';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the \r\n to the Blob, so leave footer as it is.
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        } else if(last4Bytes.endsWith('=')) {
            last4Bytes = last4Bytes.substring(0,3) + 'N';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the CR e.g. \r, still need to prepend the line feed to the footer
            footer = '\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);            

        } else {
            // Prepend the CR LF to the footer
            footer = '\r\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        }

        System.debug('---> Body: ' + bodyBlob);
        HTTPRequest req= new HttpRequest();
        req.setendpoint('https://upload.box.com/api/2.0/files/content');
        req.setmethod('POST');
        req.setHeader('Authorization','Bearer ' + creds.Access_Token__c);
        req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
        req.setBodyAsBlob(bodyBlob);
        System.debug(' res -----> :' + req.getBody());
        Http p = new Http();
        HttpResponse res= new HttpResponse();
        res = p.send( Req );

}


Creadit to: http://blog.enree.co/2013/01/salesforce-apex-post-mutipartform-data.html