Simon Fell > Its just code > April 2010

Wednesday, April 21, 2010

The API allows you to create new entries for Salesforce content by creating new ContentVersion records, you'll at a minimum need to fill out the VersionData which is the actual binary data for the file, and the pathOnClient, which is used to derive the file type, and its title. This will automatically create a new content record and put it in your personal workspace. For a twist here's an example in VisualForce rather than a SOAP based client (the Web Services API & Apex both share the same data model, so everything transfers over).

Here's the controller, called contentController, this just has a Blob property and a go method to create the actual ContentVersion row

public class contentController {

    public blob file { get; set; }
    
    public PageReference go() {
        ContentVersion v = new ContentVersion();
        v.versionData = file;
        v.title = 'from VF';
        v.pathOnClient ='/foo.txt';
        insert v;
        return new PageReference('/' + v.id);
    }
}
And for the VisualForce page, i just used the apex:inputFile to bind to it, nothing pretty, but it'll get you going. You'll probably want to do something more interesting with the title and pathOnClient properties.

<apex:form controller="contentController">
<apex:inputFile value="{!file}" />

<apex:commandbutton action="{!go}" value="go"/>
</apex:form>
</apex:page>
One variation is to have your controller expose a ContentVersion object directly, e.g.
public class contentController {

    public contentController() {
        file = new ContentVersion();
    }
    
    public ContentVersion file { get; set; }
    
    public PageReference go() {
        insert file;
        return new PageReference('/' + file.id);
    }
}	
And have the page bind directly to its properties.
<apex:page controller="contentController">
<apex:form >
<apex:inputFile value="{!file.versionData}" fileName="{!file.pathOnClient}" />
<apex:commandbutton action="{!go}" value="go"/>
</apex:form>
</apex:page>

If you want to experiment with the Content APi, you'll need to have signed up for a developer edition org recently (or go sign up a new one), and turn on the content license for the admin user.