function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kutts18kutts18 

Flex file upload

I want to upload file through my flex client to force.com databasethrough my webservice class.

Flex treats files as FileReference object, while force platform treat files as Document object.

 

Can anybody guide me how to bridge this gap between my flex client and my force webservice class?

Best Answer chosen by Admin (Salesforce Developers) 
kumokumo

Sorry for earlier post but I was able to resolve that errora nd now able to upload documents toSalesforce form Flash finally.

My earlier mistake was not creating a connection to Salesforce, here is what I did to fix that:

1. Connection need it to be created in my Panel where it is being used wich was correct.

2.  in <mx:Panel tag need to specify xmlns:salesforce="com.salesforce.*" and  <salesforce:Connection id="apex" /> do not need to provide serverUrl here

3. On login api call set server URL = https://www.salesforce.com/services/Soap/c/15.0 later on as Flex component will be locatedas static resource inside Salesforce I think I can use this..parameters.server_url and this.parameters.session_id

4. Documents must be created in specific folder I need to provide Salesforce folder ID

 

insertDocument(_refUploadFile.data, _refUploadFile.name, _refUploadFile.type, "00l80000001CLhi");

 

Next step I need to get this ID from SF system in some way by Query instead of hardcoding it liek this.

 

All Answers

etoeto

Just a suggestion, I didn't yet try it out, but it should work this way:

 

 

You need Flash Player 10 installed on your clients. Then you have access to theFileReference.load method.

 

http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html#load()

 

When load finishes, the binary data of your local filed is stored in FileReference.data as a ByteArray.

 

Use this byte array to get a base64 encoded String representation of your local file. 

 

http://livedocs.adobe.com/flex/3/langref/mx/utils/Base64Encoder.html

 

Now you can use the string to create a SObject in Flex with all required data to create a document (body will be the base64 encoded string) and insert it into SF.

 

hth

Ingo

 

kutts18kutts18

Thanks for the reply.

 

I downloaded the flex air toolkit, and i added to the lib of my flex project.

I have followed the instructions given under wiki/webservice api/flex. 

The problem is there is no Document SObject.

I am getting LoginResult SObject but Document is not there.

Document statement itself is giving error when typed in Flex Builder.

 

Can i create and pass Document SObject to my webservice class?

etoeto

SObject is a "generic" object. You just create a new SObject( "Document" ) and it is a Document. The following method is a nearly complete implementation on how to upload documents. Just add the properties you need and complete the asynchronous success and fault handlers and you should have finished this task.

 

 



public function insertDocument(content:ByteArray, documentName:String, contentType:String, folderId:String):void {

var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(content);

var so:SObject = new SObject("Document");

so.Body = enc.toString()
so.ContentType = contentType; // in your case use e.g. image/jpeg for jpg images
so.name = documentName;
so.folderId = folderId;
//use any other property for document as outlined in the APEX API

var sos:Array = new Array(1);
sos[0] = so;

apex.create(sos, new AsyncResponder(
function (result:Object):void {
trace (ObjectUtil.toString(result));
},
function (result:Object):void {
trace (ObjectUtil.toString(result));
}
)
);

}
kutts18kutts18

Thank you so much for that information.

 

But i am stills stuck because, in Flex 3.2 there is no way to retrieve byteArray data from FileReference

Object. I been trying for a few days, but i finally understood you can upload the file and retrieve all

information in server side, but you cannot use flex (NOT AIR) to open and read  file in client side.

 

This is my conclusion about using Flex to read local files in the system.

 

etoeto

According to the adobe documentation all you need ist Flash Player 10 installed on the client machine, then you should get access to the load method.

 

Just googled and found this page, maybe it will help:

 

http://sujitreddyg.wordpress.com/2008/11/04/filereference-in-flash-player-10/

kumokumo

I want to build a Flex component to upload file attachments to Salesforce objects same  as standard Saleesforce

file upload and been having trouble making it work.

I followed this post while trying to make my own Flex UI for file upload, looking at the code you have provided I may be missing something here but the API you discuss around FileReference object able to get data into byte stream is not available in SDK nor in Flex Builder IDE, I have Flex 3.2 and 3.3 sdk niether one has that method to get BytArray for file data I also have Flash player version 10.

 

It would be great if you could share some more detailed example code if available on how to connect to Salesforce from Flex and upload a file as Attachment.

Any help is appreciated.

kumokumo

I am trying to upload documents/files to Salesforce with Flex and run into a problem I used the code in Flex similar to what is provided in this post to create a Document. However what is not clear is teh endpoint where this document will be sent? Any examples of SF webservice class or VF page for endpoint taht can accept the Document created from Flex.

 

Any comments appreciated

 

I created a simple VF page with input File and from that page I can manually upload documents. But if I direct Flex code to this page it throws an error.

Here is my simple page and controller:

  here is the section of code in Flex that sends Document to the page

 

                apex.serverUrl = 'https://na6.salesforce.com/apex/MyUpload';
                apex.create(sos, new AsyncResponder(
                            function (result:Object):void {
                                trace (ObjectUtil.toString(result));
                            },
                            function (result:Object):void {
                                trace (ObjectUtil.toString(result));
                            }                                        
                            )
                 );
 

This is MyUpload VF Page:

<apex:page standardController="Document" extensions="documentExt">

<-- Upload a file and put it in your personal documents folder-->

<apex:messages />

<apex:form id="theForm">

<apex:pageBlock >

<apex:pageBlockSection >

<apex:inputFile value="{!document.body}" filename="{!document.name}"/>

<apex:commandButton value="save" action="{!save}"/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>
/*** Controller ***/
public class documentExt {

public documentExt(ApexPages.StandardController controller) {
Document d = (Document) controller.getRecord();
d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents
}

etoeto

Of course the data object is there (I can see it  right here in my code), however it is not visible, as long as you build Flex apps which shall be compatible with Flash Player 9.x. The data property is available in Flash Player 10 and above, but as long as you build applications for a version beyond, Flex Builder automatically hides any methods/properties/objects which are not available in that version.

 

There is absolutely no hint in the docs that one has to specify that in their project and maybe they think it's so obvious nobody needs to be told about it... (But - as we all here know - Adobe is not the only company with a documentation which lacks some "minor" facts - scnr).

 

However, it's simple: Just tell FlexBuilder that the minimum version of FlashPlayer is 10.x

 

Right click the project in Flex Builder, select Properties -> Flex Compiler and change "Required Flash Player version" to 10.0.0.

 

Just rebuild the project and - voilà - the Flash Player 10 objects, methods and properties are available.

 

Happy uploading!

 

 

etoeto

>I am trying to upload documents/files to Salesforce with Flex and run into a problem I used the

>code in Flex similar to what is provided in this post to create a Document. However what is not

>clear is teh endpoint where this document will be sent? Any examples of SF webservice class or

>VF page for endpoint taht can accept the Document created from Flex.

 

I would strongly suggest to open a new thread for this question as it is not really related to the topic and it's hard to follow two different topics in one thread.

 

And keep in mind to give as much information as possible (but not too much), in this case:

- what error

- what is the relevant part of your flex code (the code which uploads the file)

 

hth

Ingo

kumokumo

Thank you for the Flash 10 setup advice, I did resolve that problem by setting Flex builder SDK and environment to use Flash 10 player using instructions here: http://opensource.adobe.com/wiki/display/flexsdk/Targeting+Flash+Player+10. I am adble to laod the file data into memory as ByteArray inside Flex component. But I am not able to create a Document object in Salesforce. I am getting an error that server URL need to be set to URL returned by Login. On intialization I am able to login with my SFDC credentials (running in debug from FlexBuilder). Understandable that once Flex componenet is loaded into SF org I will be abble to get a SessionID from the system to call APIs.

 

The problem is the error on creaing Document - IOErrorEvent UNKNOWN_EXCEPTION: Destination URL not reset. The URL returned from login must be set in the SforceService. Typically using SF webservices API in Java after login I would get result object and will set Server URL to the URL returned by the login method. In Flex I see the serverURL is set to my default value: https://www.salesforce.com/services/Soap/c/15.0 after call to apex.login method no errors reported and no result so I cannot set this URL.

I try to check for porperties in the apex inside Flex but they are all NULL

 

var lr:LoginResult = apex.loginResult;
var app_url:String = apex.applicationUrl;
var app_domain:String = apex.applicationDomain;       
var app_n:String = apex.applicationServerName;

 

I setup SF connection in Flex component in the Panel instead of Application as I have seen it done in several examples. I did not see example on how to setup connection in Panel. Not sure if this is a problem although I did try to set connection in Application still got same error? My connection code looks like this:

 

<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="*" xmlns:salesforce="http://www.salesforce.com/"
    layout="vertical" width="100%" minWidth="400" height="100%" minHeight="200"
    title="Upload Files" creationComplete="initCom();">
    <salesforce:Connection id="apex" serverUrl="https://www.salesforce.com/services/Soap/c/15.0" />

 

<mx:Script>
        <![CDATA[
            import com.salesforce.results.LoginResult;

            import mx.controls.*;
            import mx.managers.*;
            import mx.events.*;
            import flash.events.*;
            import flash.net.*;

    import mx.collections.ArrayCollection;
    import com.salesforce.results.QueryResult;
    import mx.utils.ObjectUtil;
    import mx.controls.Alert;
    import com.salesforce.AsyncResponder;
    import com.salesforce.objects.LoginRequest;
    import mx.utils.Base64Encoder   
    import com.salesforce.objects.SObject;
    import com.salesforce.AsyncResponder;
    import flash.net.FileReference;
 

            // Initalize
            private function initCom():void {
                // SF Login test
                apex.login(  new LoginRequest({
                server_url : 'https://www.salesforce.com/services/Soap/c/15.0',//this.parameters.server_url,
                //session_id : this.parameters.session_id,
                // put your own info here to test standalone
                username : '<USER ID>',
                password : '<PASSWORD>',
                callback : new AsyncResponder(render)
                }));
                        
            }

 

The render function is login Callback looks like this, but in debug mode it has never been called. I am guessing this may mean that my login to SF ORG has not been correct?

 

            private function render(result:Object):void {
                // Stub function
                var str:String = ObjectUtil.toString(result);
                trace (ObjectUtil.toString(result));               
            }
 

 

 

I get a trace of Error after trying to call apex.create method to create a Document here is relevant Exception message the full trace is large to post here:

 

<faultcode xmlns:ns1="urn:fault.enterprise.soap.sforce.com">ns1:UNKNOWN_EXCEPTION</faultcode>
   <faultstring>UNKNOWN_EXCEPTION: Destination URL not reset. The URL returned from login must be set in the SforceService</faultstring>
   <detail>
    <sf:fault xsi:type="sf:UnexpectedErrorFault" xmlns:sf="urn:fault.enterprise.soap.sforce.com">
     <sf:exceptionCode>UNKNOWN_EXCEPTION</sf:exceptionCode>
     <sf:exceptionMessage>Destination URL not reset. The URL returned from login must be set in the SforceService</sf:exceptionMessage>
    </sf:fault>
   </detail>

kumokumo

Sorry for earlier post but I was able to resolve that errora nd now able to upload documents toSalesforce form Flash finally.

My earlier mistake was not creating a connection to Salesforce, here is what I did to fix that:

1. Connection need it to be created in my Panel where it is being used wich was correct.

2.  in <mx:Panel tag need to specify xmlns:salesforce="com.salesforce.*" and  <salesforce:Connection id="apex" /> do not need to provide serverUrl here

3. On login api call set server URL = https://www.salesforce.com/services/Soap/c/15.0 later on as Flex component will be locatedas static resource inside Salesforce I think I can use this..parameters.server_url and this.parameters.session_id

4. Documents must be created in specific folder I need to provide Salesforce folder ID

 

insertDocument(_refUploadFile.data, _refUploadFile.name, _refUploadFile.type, "00l80000001CLhi");

 

Next step I need to get this ID from SF system in some way by Query instead of hardcoding it liek this.

 

This was selected as the best answer