cancel
Showing results for 
Search instead for 
Did you mean: 

problem upload file with REST API, StringPart()

magarcia_sm
Star Contributor
Star Contributor
Hi there,
I'm trying to upload a file with the REST API, but when uploading not find the file.
I know that the error is in the following lines, I've tried everything but I do not know who put exactly.


new StringPart("siteid", "HULA"),
new StringPart("containerid", "documentLibrary"),
new StringPart("uploaddirectory", "/facultativos")


I saw another post with the same problem but the proposed solutions did not work me.
Any ideas about what could be wrong?
Some indications that put exactly in these fields?

Thanks a lot in advance!!


Code with the message:

response = <?xml version="1.0" encoding="UTF-8"?>
<ticket>TICKET_277b2045c4d75c96e1ced32ecbc15ae307546e91</ticket>

ticket = TICKET_277b2045c4d75c96e1ced32ecbc15ae307546e91
The upload url:::http://localhost:8080/alfresco/service/api/upload?alf_ticket=TICKET_277b2045c4d75c96e1ced32ecbc15ae3...
statusLine>>>404……
status line
HTTP/1.1 404 No Encontrado
body
{
    "status" :
  {
    "code" : 404,
    "name" : "Not Found",
    "description" : "Requested resource is not available."
  }, 
 
  "message" : "Site (HULA) not found.", 
  "exception" : "",
 
  "callstack" :
  [
       
  ],
 
  "server" : "Community v5.0.0 (c r91299-b145) schema 8.009",
  "time" : "02-jun-2015 13:40:32"
}



Code Upload.java:


package Conexion_HULA;

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

import org.apache.commons.httpclient.HttpClient;
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;

public class Upload {

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

         String urlString = "http://localhost: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", "workspace://SpacesStore/50645ce9-6abc-4ea6-93ea-dd7bf65304d6"),
               new StringPart("description", description),

               // modify this according to where you wanna put your content
               new StringPart("siteid", "HULA"),
               new StringPart("containerid", "documentLibrary"),
               new StringPart("uploaddirectory", "/facultativos")
         };
         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://localhost:8080/alfresco" + "/service/api/login?u=" + "admin" + "&pw=" + "admin";

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

      File f = new File("D:/bloqueo1.pdf");

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

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

gravitonian
Star Collaborator
Star Collaborator
Hi,

I assume you are developing a stand-alone Alfresco client. Try using CMIS and OpenCMIS library for this instead, it will give you a standard approach, hiding some of the details:

Here is an example on how to upload a file and set a type at the same time:


public Document createDocumentFromFileWithCustomType(Session session) {
        String documentName = "somefile.pdf";
        File file = new File("/home/martin/Documents/somefile.pdf");
        Folder parentFolder = session.getRootFolder();

        // Check if document already exist, if not create it
        Document newDocument = (Document) getObject(session, parentFolder, documentName);
        if (newDocument == null) {
            // Setup document metadata
            Map<String, Object> newDocumentProps = new HashMap<String, Object>();
            newDocumentProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
            newDocumentProps.put(PropertyIds.NAME, documentName);

            InputStream is = null;
            try {
                // Setup document content
                is = new FileInputStream(file);
                String mimetype = "application/pdf";
                ContentStream contentStream = session.getObjectFactory().createContentStream(
                        documentName, file.length(), mimetype, is);

                // Create versioned document object
                newDocument = parentFolder.createDocument(newDocumentProps, contentStream, VersioningState.MAJOR);
                logger.info("Created new document: " + getDocumentPath(newDocument) +
                    " [version=" + newDocument.getVersionLabel() + "][creator=" + newDocument.getCreatedBy() +
                    "][created=" + date2String(newDocument.getCreationDate().getTime()) + "]");

                // Close the stream to handle any IO Exception
                is.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                IOUtils.closeQuietly(is);
            }
        } else {
            logger.info("Document already exist: " + getDocumentPath(newDocument));
        }

        return newDocument;
    }

In this case we set the generic/base CMIS type that corresponds to cm:content.
Note also that the document is created in the Root folder of Alfresco (i.e. Company Home).

How to create a session:


    public Session getSession(String connectionName, String username, String pwd) {
        Session session = connections.get(connectionName);
        if (session == null) {
            logger.info("Not connected, creating new connection to Alfresco with the connection id ("
                    + connectionName + ")");

            // No connection to Alfresco available, create a new one
            SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put(SessionParameter.USER, username);
            parameters.put(SessionParameter.PASSWORD, pwd);
            parameters.put(SessionParameter.ATOMPUB_URL,
                    "http://localhost:8080/alfresco/api/-default-/cmis/versions/1.1/atom");
            parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
            parameters.put(SessionParameter.COMPRESSION, "true");
            parameters.put(SessionParameter.CACHE_TTL_OBJECTS, "0");

            // If there is only one repository exposed (e.g. Alfresco), these
            // lines will help detect it and its ID
            List<Repository> repositories = sessionFactory.getRepositories(parameters);
            Repository alfrescoRepository = null;
            if (repositories != null && repositories.size() > 0) {
                logger.info("Found (" + repositories.size() + ") Alfresco repositories");
                alfrescoRepository = repositories.get(0);
                logger.info("Info about the first Alfresco repo [ID=" + alfrescoRepository.getId() +
                        "][name=" + alfrescoRepository.getName() +
                        "][CMIS ver supported=" + alfrescoRepository.getCmisVersionSupported() + "]");
            } else {
                throw new CmisConnectionException(
                        "Could not connect to the Alfresco Server, no repository found!");
            }

            // Create a new session with the Alfresco repository
            session = alfrescoRepository.createSession();

            // Save connection for reuse
            connections.put(connectionName, session);
        } else {
            logger.info("Already connected to Alfresco with the connection id (" + connectionName + ")");
        }

        return session;
    }


And the getObject method:

  private CmisObject getObject(Session session, Folder parentFolder, String objectName) {
        CmisObject object = null;

        try {
            String path2Object = parentFolder.getPath();
            if (!path2Object.endsWith("/")) {
                path2Object += "/";
            }
            path2Object += objectName;
            object = session.getObjectByPath(path2Object);
        } catch (CmisObjectNotFoundException nfe0) {
            // Nothing to do, object does not exist
        }

        return object;
    }

</code>

ishaan
Champ in-the-making
Champ in-the-making
Hi,

The error clearly says, the site "HULA" doesn't exists, you can create a new site with same name, or you can give an existing siteid, as well as you have to create "/facultativos" under the newly created site, rest alfresco will do.

Regards,