cancel
Showing results for 
Search instead for 
Did you mean: 

Can someone PLEASE provide just ONE example of an upload

dallinns
Champ on-the-rise
Champ on-the-rise
I am ripping my hair out trying to get the upload webscript (alfresco/service/api/upload) to work. It seems simple enough but I can't get it to work for the life of me.

First of all, which parameters are necessary for NEW FILE UPLOAD (i.e. How can I possibly provide an updatenoderef if I'm not updating a node?). I don't want to update a node, all i want is to take one simple file off of my hard drive, and upload it to Alfresco into the company home folder. It asks for uploaddirectory and containerid. In what format does it want these? Do I provide the UUID of Company Home? Something else? How do I provide an uploaddirectory?

I'm sure this is all quite simple, but I just need a fully fleshed out example of an HTML form or a curl request which shows what is needed and in what format, etc.
13 REPLIES 13

viron82
Champ in-the-making
Champ in-the-making
I also tried to implement uploading file and ask lots of questions on the forum, but no one has answered this simple question. Somebody can answer?

zezom
Champ in-the-making
Champ in-the-making
Hi Guys,
This is a piece of curl code I found that uses curl to upload to alfresco.

In the end I could only get it to upload under the Sites directory for Alfresco Share. I think this is a limitation of the ${ALFRESCO_SERVER}/service/api/upload URL so in the end I wrote my own web script to handle uploads.

I hope this helps. Have a search around for key words like siteid and containerid for more info, although there isn't much that I could find.

P.S. you will need to modify the USERNAME and PASSWORD variables.

#!/bin/bash
#
# Alfresco upload script with CURL by LouiSe@louise.hu
#
# Usage: alfresco_uploader.sh
#
# ./alfresco_uploader.sh /tmp/some.pdf someSite documentLibrary someDir
#

ALFRESCO_SERVER=http://localhost:8080/alfresco
USERNAME="admin"
PASSWORD="admin"

#CURL_VERBOSE=-v
CURL_VERBOSE=-s
CURL_METHOD=POST
FILENAME=`basename $1`
MIMETYPE=`file –brief –mime-type $1`
UPLOAD_SERVICE_URL=${ALFRESCO_SERVER}/service/api/upload

echo "Uploading: ${FILENAME} ($MIMETYPE) to ${ALFRESCO_SERVER}"

curl ${CURL_VERBOSE} -k -X ${CURL_METHOD} \
    –user "${USERNAME}":"${PASSWORD}" \
    -F filedata=@$1 -F siteid="$2" -F containerid="$3" \
    -F uploaddirectory="$4" \ -F filename="${FILENAME}" \
    -F contenttype="${MIMETYPE}" "${UPLOAD_SERVICE_URL}" \
    | grep 'description' | cut -d ':' -f 2 | tr -d '\"'

echo "curl ${CURL_VERBOSE} -k -X ${CURL_METHOD} –user \"${USERNAME}\":\"${PASSWORD}\" -F filedata=@$1 -F siteid=\"$2\" -F containerid=\"$3\" -F uploaddirectory=\"$4\" -F filename=\"${FILENAME}\" -F contenttype=\"${MIMETYPE}\" \"${UPLOAD_SERVICE_URL}\""

openpj
Elite Collaborator
Elite Collaborator
In the Alfresco wiki I have updated the Upload Form example that now should work on the latest version of Alfresco:
http://wiki.alfresco.com/wiki/Web_Scripts_Examples#Upload_Form
Hope this helps.

nandhakumars
Champ in-the-making
Champ in-the-making
Hi,

I'm trying to upload new version for the document using the web service. I'm having a variable called isNew, if its value is true it will upload a new file in Alfresco else if its false, should upload the file as newer version of that file. When i fire the request, from alfresco i'm getting Upload success response but the version is getting uploaded bur i'm able to see a message as "Just now modified" in the document folder but the file still not modified. Can you guys help me with this? Have you done this already?

Thanks in Advance

oluwasegzy
Champ in-the-making
Champ in-the-making
Is there a JAVA class equivalent of this Javascript you uploaded?

Please can u show me cos am having issues with the my JAVA BACKED file upload

zliu
Champ in-the-making
Champ in-the-making
Here is an example in Java. The method uploads a file using Commons http client and Alfresco RESTful API. It seems to me that site id, container id and upload directory, in addition to the file data itself, are the minimum parameters to upload a file. Assuming that you have a folder "abc" created in "Document Library" under site "demo", the parameters would be
siteId="demo"
containerId="documentlibrary"
uploadDirectory="/abc"

Note that the code uses alf_ticket for authentication when calling upload, which you can get from the login webscript. Hope this helps.

   public String upload(File file, String siteId, String containerId, String uploadDirectory) {

      String json = null;

      DefaultHttpClient httpclient = new DefaultHttpClient();

            HttpHost targetHost = new HttpHost("localhost", 8080, "http");

      try {
         HttpPost httppost = new HttpPost("/alfresco/service/api/upload?alf_ticket="
               + this.ticket);

         FileBody bin = new FileBody(file);
         StringBody siteid = new StringBody(siteId);
         StringBody containerid = new StringBody(containerId);
         StringBody uploaddirectory = new StringBody(uploadDirectory);

         MultipartEntity reqEntity = new MultipartEntity();
         reqEntity.addPart("filedata", bin);
         reqEntity.addPart("siteid", siteid);
         reqEntity.addPart("containerid", containerid);
         reqEntity.addPart("uploaddirectory", uploaddirectory);

         httppost.setEntity(reqEntity);

         log.debug("executing request:" + httppost.getRequestLine());

         HttpResponse response = httpclient.execute(targetHost, httppost);

         HttpEntity resEntity = response.getEntity();

         log.debug("response status:" + response.getStatusLine());

         if (resEntity != null) {
            log.debug("response content length:"
                  + resEntity.getContentLength());

            json = EntityUtils.toString(resEntity);
            log.debug("response content:" + json);
         }

         EntityUtils.consume(resEntity);
      } catch (Exception e) {
         throw new RuntimeException(e);
      } finally {
         httpclient.getConnectionManager().shutdown();
      }

      return json;
    }

openpj
Elite Collaborator
Elite Collaborator
This is an example of an Upload Java-Backed WebScripts.
Hope this helps  :wink:

public class UploadWebScript extends DeclarativeWebScript {

   private static Log log = LogFactory.getLog(UploadWebScript.class);
   
   private NodeService nodeService;
   private ContentService contentService;
   private TransactionService transactionService;
   private DataDictionaryHelper dataDictionaryHelper;
   private MimetypeService mimetypeService;
   
    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }
   
   public void setContentService(ContentService contentService) {
      this.contentService = contentService;
   }

   public void setTransactionService(TransactionService transactionService) {
      this.transactionService = transactionService;
   }

   public void setDataDictionaryHelper(DataDictionaryHelper dataDictionaryHelper) {
      this.dataDictionaryHelper = dataDictionaryHelper;
   }
   
    public void setMimetypeService(MimetypeService mimetypeService) {
        this.mimetypeService = mimetypeService;
    }
   
    @Override
    protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
       I18NUtil.setLocale(Locale.ENGLISH);
   Map<String, Object> model = new HashMap<String, Object>();
       UserTransaction tx = transactionService.getUserTransaction(false);
       try {
         tx.begin();
           NodeRef newNode = createNewNode(req);
         tx.commit();
           model.put("newNode", newNode);
       } catch (RollbackException e) {
         log.warn(e);
         status.setCode(500);
         status.setMessage(e.getLocalizedMessage());
         status.setException(e);
         status.setRedirect(true);
      } catch (Exception e) {
         log.warn(e);
         status.setCode(500);
         status.setMessage(e.getLocalizedMessage());
         status.setException(e);
         status.setRedirect(true);
         try {
            tx.rollback();
         } catch (Exception e1) {
            log.error("Transaction rollback failed");
            log.error(e1);
         }
      }
      return model;
    }

   private NodeRef createNewNode(WebScriptRequest req) {
           if (log.isDebugEnabled()) {
         log.debug("Creating new node of type '" + req.getParameter("type") + "' under node " + req.getParameter("uuid"));
      }

        Map<String, String> params = getRequestParametersAsMap(req);
        Map<QName, Serializable> properties = dataDictionaryHelper.convertParametersToProperties(params);
        NodeRef parent = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, req.getParameter("uuid"));
       
        QName contentTypeQname = QName.createQName(YOUR_CUSTOM_NAMESPACE, req.getParameter("type"));

        FormData fd = (FormData) req.parseContent();
        FormField[] fields = fd.getFields();
        for (FormField field : fields) {
           if (field.getIsFile()) {
             String name = field.getFilename();
               properties.put(ContentModel.PROP_NAME, name);
               ChildAssociationRef children = nodeService.createNode(parent, ContentModel.ASSOC_CONTAINS,
                     DataDictionaryHelper.getAssocNameFromFileName(name), contentTypeQname, properties);
               NodeRef newNode = children.getChildRef();
             
              ContentWriter writer = contentService.getWriter(newNode, ContentModel.PROP_CONTENT, true);
              writer.setMimetype(mimetypeService.guessMimetype(name));
              writer.putContent(field.getInputStream());
              return newNode;
         }
        }
        log.warn("Request did not have a file");
        return null;
   }

   private Map<String, String> getRequestParametersAsMap(WebScriptRequest req) {
      Map<String, String> params = new HashMap<String, String>();
      for (String name : req.getParameterNames()) {
         params.put(name, req.getParameter(name));
      }
      return params;
   }
}

dnallsopp
Champ in-the-making
Champ in-the-making
Simple curl example, tested against Alfresco Community 4.0.d on Windows XP
curl -v -X POST -F filedata=@myUpload.doc -F siteid=mysite -F containerid=documentLibrary -F uploaddirectory=/uploads http://username:password@localhost:8080/alfresco/service/api/upload
This will upload into documentLibrary/uploads within the specific Share site (mysite). Note that the user performing the upload must be a member of that Share site (and presumably needs at least Contributor access?).

I'm unsure why the leading slash is needed for the uploaddirectory, since the script seems to remove it again. But omitting it causes the file to be saved into the parent folder i.e. documentLibrary!

The actual webscript is located in tomcat\webapps\alfresco\WEB-INF\classes\alfresco\templates\webscripts\org\alfresco\repository\upload - looking at the source is the best way to understand it as the online Alfresco documentation is not very detailed (http://docs.alfresco.com/4.0/index.jsp?topic=%2Fcom.alfresco.enterprise.doc%2Freferences%2FRESTful-U...)

zuzoovn
Champ in-the-making
Champ in-the-making
Hi, how can i upload in Android with Restful API?
Regards