Home

Uploading file to alfresco repository using AlfrescoRest API

You are here

13 posts / 0 new
Last post
Uploading file to alfresco repository using AlfrescoRest API

Hi all,
I am developing a e-commerce project for magazines. I am using alfresco 3.4.c as Repository for storing content and I am using Jerse client and alfresco REST API to connect to alfresco repository. In this project, I have to write a Jersey client program to upload content to alfresco repository.
My Jersey Client program is below. In this program, I am uploading Html file, but I want to upload any file (ex: pdf , word file etc).

I used the built in rest service /alfresco/service/api/upload to upload file into alfresco repository. But it is not uploading content into repository.

public class AlfrescoFileUpload {

public static void main(String[] args) throws IOException{

ClientConfig config = new DefaultClientConfig();

Client client = Client.create(config);
BufferedReader br=null;

WebResource webResource = client.resource("http://127.0.0.1:8888/alfresco/service/api/login");

MultivaluedMap queryParams = new MultivaluedMapImpl();
queryParams.add("u", "admin");
queryParams.add("pw", "alfresco");

String s = webResource.queryParams(queryParams).get(String.class);

client.addFilter(new HTTPBasicAuthFilter("admin", "alfresco"));

WebResource wr= client.resource("http://localhost:8888/alfresco/service/api/upload");

File file=new File("/home/sivakiranm/drag.html");

FormDataMultiPart form = new FormDataMultiPart();

form.field("filedata", "@drag.html");
form.field("username", "admin");
form.field("password", "alfresco");

form.field("siteid","gopustak");

form.field("containerid","CompanyHome");
form.field("uploaddirectory","documentLibrary");
form.field("filename", "drag.html");
form.field("noderef","nodeRef=workspace://SpacesStore/6eabdd9c-0489-4d71-8c43-c8ed4c3c6c85");
// form.field("updatenoderef","alfresco/service/api/node/workspace/SpacesStore/23q1-34fr-5ab4-t4vf/drag.html");
form.field("description","this is html file");
form.field("contenttype","application/html");
form.field("majorversion","1.0");
form.field("overrite","yes");
form.field("thumbnails", "yes");


form.field("filename", file.getName());

form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE));

//InputStreamProvider response = wr.type(MediaType.MULTIPART_FORM_DATA).post(InputStreamProvider.class, form);

InputStream in=wr.type(MediaType.MULTIPART_FORM_DATA).post(InputStream.class,form);

OutputStream out=new FileOutputStream(form);
byte buf[]=new byte[1024];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
out.close();
in.close();
System.out.println("\nFile is created....................");
}

}
}

Can any one help me how to upload file to Alfreco Repository using Rest api?

Re: Uploading file to alfresco repository using AlfrescoRest

try this :

FileUpload.java :

/**
*
*/
package com;

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;

/**
* @author aaa
*
*/
public class FileUpload {

public static void uploadDocument(String authTicket, File fileobj,
String filename, String filetype, String description,
String destination) {
try {

String urlString = "http://192.168.100.152:8080/alfresco/service/api/upload?alf_ticket="
+ authTicket;
System.out.println("The upload url:::" + urlString);
HttpClient client = new HttpClient();

PostMethod mPost = new PostMethod(urlString);
// File f1 =fileobj;
Part[] parts = {
new FilePart("filedata", filename, fileobj, filetype, null),
new StringPart("filename", filename),
new StringPart("description", description),
//new StringPart("destination", destination),
new StringPart("description", description),

//modify this according to where you wanna put your content
new StringPart("siteid", "ursite"),
new StringPart("containerid", "documentLibrary"),
//new StringPart("uploaddirectory", "/Company Home")
};
mPost.setRequestEntity(new MultipartRequestEntity(parts, mPost
.getParams()));
int statusCode1 = client.executeMethod(mPost);
System.out.println("statusLine>>>" + statusCode1 + "......"
+ "\n status line \n"
+mPost.getStatusLine() + "\nbody \n" +mPost.getResponseBodyAsString());
mPost.releaseConnection();

} catch (Exception e) {
System.out.println(e);
}
}

public static void main(String args[]) throws IOException {
// SimpleUpload aw=new SimpleUpload();
// String Ticket=aw.login();
// String ticket="TICKET_3e61ccfa8a11690b10e1a2fb0eeee2c5583b0043";

// aritz : not using predefined method to get credential
String alfrescoTiccketURL = "http://192.168.100.152:8080/alfresco"
+ "/service/api/login?u=" + "admin" + "&pw=" + "admin";

InteractiveAuthentication ticket = new InteractiveAuthentication();
String ticketURLResponse = ticket.getTicket(alfrescoTiccketURL);

File f = new File("C:/Upload_Content.pdf");

// FileInputStream is=new FileInputStream(f);
uploadDocument(ticketURLResponse, f, "Upload_Content.pdf",
"application/pdf", "description", null);

// uploadDocument("TICKET_3ef085c4e24f4e2c53a3fa72b3111e55ee6f0543",
// f,"47.bmp","image file","application/jpg","workspace://SpacesStore/65a06f8c-0b35-4dae-9835-e38414a99bc1");
}

}

InteractiveAuthentication :

package com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
import org.apache.commons.httpclient.auth.CredentialsProvider;
import org.apache.commons.httpclient.auth.NTLMScheme;
import org.apache.commons.httpclient.auth.RFC2617Scheme;
import org.apache.commons.httpclient.methods.GetMethod;

import com.InteractiveAuthenticationExample.ConsoleAuthPrompter;

public class InteractiveAuthentication {

public InteractiveAuthentication() {
super();
}

public String getTicket(String url) throws IOException {

HttpClient client = new HttpClient();
client.getParams().setParameter(
CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());
GetMethod httpget = new GetMethod(url);
httpget.setDoAuthentication(true);

//aritz
String response = null;
String ticketURLResponse = null;

try {
// execute the GET
int status = client.executeMethod(httpget);

//aritz
if (status != HttpStatus.SC_OK) {
System.err.println("Method failed: " + httpget.getStatusLine());
}

// print the status and response
// System.out.println(httpget.getStatusLine().toString());
// System.out.println(httpget.getResponseBodyAsString());

response = new String(httpget.getResponseBodyAsString());
System.out.println("response = "+response);

int startindex= response.indexOf("")+8;
int endindex = response.indexOf("");

ticketURLResponse = response.substring(startindex, endindex);
System.out.println("ticket = "+ticketURLResponse);

} finally {

// release any connection resources used by the method
httpget.releaseConnection();
}
return ticketURLResponse;
}

public class ConsoleAuthPrompter implements CredentialsProvider {

private BufferedReader in = null;
public ConsoleAuthPrompter() {
super();
this.in = new BufferedReader(new InputStreamReader(System.in));
}

private String readConsole() throws IOException {
return this.in.readLine();
}

public Credentials getCredentials(
final AuthScheme authscheme,
final String host,
int port,
boolean proxy)
throws CredentialsNotAvailableException
{
if (authscheme == null) {
return null;
}
try{
if (authscheme instanceof NTLMScheme) {
System.out.println(host + ":" + port + " requires Windows authentication");
System.out.print("Enter domain: ");
String domain = readConsole();
System.out.print("Enter username: ");
String user = readConsole();
System.out.print("Enter password: ");
String password = readConsole();
return new NTCredentials(user, password, host, domain);
} else
if (authscheme instanceof RFC2617Scheme) {
System.out.println(host + ":" + port + " requires authentication with the realm '"
+ authscheme.getRealm() + "'");
System.out.print("Enter username: ");
String user = readConsole();
System.out.print("Enter password: ");
String password = readConsole();
return new UsernamePasswordCredentials(user, password);
} else {
throw new CredentialsNotAvailableException("Unsupported authentication scheme: " +
authscheme.getSchemeName());
}
} catch (IOException e) {
throw new CredentialsNotAvailableException(e.getMessage(), e);
}
}
}
}

Thank you. This worked great!

Thank you. This worked great!

I know this is a few months

I know this is a few months old now, but I'm hoping someone knows the answer. I have pretty much plagiarized this code and put it into practice. But one thing I can't figure out is how, if I'm uploading a file with the same name as one which already exists, it can be made to overwrite the old file, increasing its version number. I thought that it might be the "overwrite" property (which I implemented by adding the line:

new StringPart("overwrite","true")

but this didn't work. What happens instead is another file is created with a "-1" or "-2" suffix to the file name.

Does the property which would cause the file to be overwritten exist?

Thanks,

Steve

While uploading a file, the

While uploading a file, the webscript first checks if there is file with the same name in the destination folder or not. If it is present and it has cm:versionable aspect applied and if you have provided input parameter overwrite as true to the webscript, it will overwrite the content of existing file with the newly uploaded one. Hence, overwrite attribute only works in case there is an existing file already available with the same name having cm:versionable aspect applied on it. Otherwise generally it will append the counters like 1,2 etc on the filename which already exists as you are currently getting it.

Hope this helps.

Thanks & Regards,
Ramesh Chauhan
CIGNEX Datamatics

The organization I work at - CIGNEX Datamatics
My book contribution on Alfresco - Learning Alfresco Web Scripts
My blog - http://alfresco-for-developers.blogspot.in

That works fine, thanks very

That works fine, thanks very much for the tip.

Re: Uploading file to alfresco repository using AlfrescoRest

Hi, melttech.

The code you posted works correctly. However, I need to upload a file on a specific subdirectory.

How to do this using RESTful and passing the uuid destination?

ps. Sorry for my english!

grateful!

Re: Uploading file to alfresco repository using AlfrescoRest

Hi,

Anyway, I could understand what I was doing wrong!

The parameter "siteid" deletes the parameter "destination".

I was trying to use both, so it was not working. It was just remove the "siteid" that the parameter "destination" started to function as it should.

Part[] parts = {
	new FilePart("filedata", filename, file, filetype, null),
	new StringPart("filename", filename),
	new StringPart("description", "description"),
	// new StringPart("siteid", "yoursite"),
	// new StringPart("containerid", "documentLibrary"),
        new StringPart("destination", "workspace://SpacesStore/7118e242-86b1-489a-ac2e-193364ccf6e4"),
}

Thank you for everything!

Filename

Hello,

everytime I upload a file using REST API, my file receives the name of the file that is beeing uploaded but not the name I specified in my json string.

$json = array
(
"filename" => 'TEST.PDF',
"destination" => 'workspace://SpacesStore/'.$parentID,
"filedata" => $pdf
);

What do I have to change, that my file will be named as the file name that I specify in my json string?

Thank you
---
pyt

Destination not found while uploading

Hi all,
this is my first post.
I'm trying to upload a pdf file to Alfresco and i have a problem.
I get this error: Destination [a path] not found.
I used this code:
Part[] parts = {
new FilePart("filedata", filename, fileobj, filetype, null),
new StringPart("filename", filename),
new StringPart("description", description),
new StringPart("destination", "workspace://Company Home/User Homes/Salesforce")
};

I know the error is in the destination since i wrote workspace://Company Home/User Homes/Salesforce.
I saw melttech instead wrote: workspace://SpacesStore/65a06f8c-0b35-4dae-9835-e38414a99bc1
Quite different, i imagine each folder inside a workspace has a ID such as 65a06f8c-0b35-4dae-9835-e38414a99bc1.
So my question is, if i want to upload my file on the location /Company Home/User Homes/Salesforce, how can i specify the destination?
Thank you and sorry for my english!

upload

1.Using the Node Browser to get the node reference of companyhome ,you can refer to below url on how to use Node Browser
http://docs.alfresco.com/4.1/index.jsp?topic=%2Fcom.alfresco.enterprise.doc%2Ftasks%2Fadminconsole-nodebrowser.html
2. Pass company home refernce to destination parameter(the folder NodeRef where the node will be created)
3.Pass "User Homes/Salesforce" to uploaddirectory parameter(name of the folder in the destination where the document will be uploaded).
Following is sample code.

			Part[] parts = {
new FilePart("filedata", filename, fileobj, filetype, null),
new StringPart("filename", filename),
new StringPart("description", description),
 
new StringPart("destination", "workspace://SpacesStore/ce55a850-b1c7-43c7-a600-b5c58a985429"),
new StringPart("uploaddirectory", "/TESTFOLDER1")
};

If this post was helpful, please click Yes on the Post Rating

How can i get noderef of

How can i get noderef of company home by in javascript without hardcoding

companyhome

companyhome itself is a root object,you can use it directly ,why do you want it to be softcoding ?
If you don't want to use it directly ,you can write a javascript funtcion and in the function use javascript search api to search "company home" node,then return companyhome object

If this post was helpful, please click Yes on the Post Rating