cancel
Showing results for 
Search instead for 
Did you mean: 

Upload error

davtrasher
Champ in-the-making
Champ in-the-making
Hi,
I try to upload files to alfresco2.9c with rest api. The upload succeed but files are empty
post method:
String adresse= "/alfresco/wcservice/sample/upload?";      try {         //encodage des paramètres de la requête         String donnees = URLEncoder.encode("filename", "UTF-8")+         "="+URLEncoder.encode(nomDoc, "UTF-8");         donnees += "&"+URLEncoder.encode("content", "UTF-8")+         "=" + URLEncoder.encode(content, "UTF-8");         donnees += "&"+URLEncoder.encode("mimetype", "UTF-8")+         "=" + URLEncoder.encode(mimetype, "UTF-8");         donnees += "&"+URLEncoder.encode("title", "UTF-8")+         "=" + URLEncoder.encode(title, "UTF-8");         donnees += "&"+URLEncoder.encode("description", "UTF-8")+         "=" + URLEncoder.encode(description, "UTF-8");         donnees += "&"+URLEncoder.encode("TypeExam", "UTF-8")+         "=" + URLEncoder.encode(TypeExam, "UTF-8");         donnees += "&"+URLEncoder.encode("nodeid", "UTF-8")+         "=" + URLEncoder.encode(nodeid, "UTF-8");         donnees += "&"+URLEncoder.encode("ticket", "UTF-8")+         "=" + URLEncoder.encode(getTicket(), "UTF-8");         //création de la connection         URL url = new URL(getUrlContext()+adresse);         URLConnection conn = url.openConnection();         conn.setDoOutput(true);         //envoi de la requête         writer = new OutputStreamWriter(conn.getOutputStream());         writer.write(donnees);         writer.flush();         //lecture de la réponse         reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));         while ((ligne = reader.readLine()) != null) {            System.out.println(ligne);         }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
upload webscript :
Code: Tout sélectionnervar filename = null;var content = null;var title = "";var description = "";var nodeid = "";var TypeExam = "";var mimetype = "";// locate file attributesfilename = args['filename'];content = args['content'];mimetype = args['mimetype'];title = args['title'];description = args['description'];nodeid = args ['nodeid'];TypeExam = args['TypeExam'];// ensure mandatory file attributes have been locatedif (filename == undefined || content == undefined){  status.code = 400;  status.message = "Uploaded file cannot be located in request";  status.redirect = true;}else{// get folder to upload into with nodeidif ((nodeid) && (nodeid != "")){   model.folder = search.findNode("workspace://SpacesStore/" +nodeid);}      upload = model.folder.createFile(filename) ;            upload.specializeType("{my.new.model}compte_rendu");            upload.properties.content.setContent(content);            upload.properties.content.encoding = "UTF-8";            upload.properties.content.mimetype = mimetype;            upload.properties.title = title;            upload.properties.description = description;            upload.properties.TypeExam = TypeExam;            upload.save();   // setup model for response template  model.upload = upload;}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
When I use upload.properties.content.write(content), the method is not found and content is "null" and when I use setContent(content), the document has the right size and pages number but is empty.

I try this too:
upload.properties.content.content = content;‍‍‍


Do you understand what happened?
Thanks
12 REPLIES 12

davtrasher
Champ in-the-making
Champ in-the-making
I try "createNode" and "upload.properties.content.content = content"  without success.

      var props = new Array();      props["my:typeExam"] = typeExam;      props["my:dateExam"] = dateExam;      props["my:correspondant"] = correspondant;      upload = model.folder.createNode(filename,"my:compterendu",props);      upload.properties.content.encoding = "UTF-8";      upload.properties.content.content = content;      upload.properties.title = title;      upload.save();       upload.addAspect("cm:titled"); ‍‍‍‍‍‍‍‍‍‍‍

Here is the method which read the file content and give it to the post method.

private String readFileAsString(String filePath)   throws java.io.IOException{      StringBuffer fileData = new StringBuffer(1000);      BufferedReader reader = new BufferedReader(            new FileReader(filePath));      while (reader.ready()) {         String s = reader.readLine();         fileData.append(s);      }      reader.close();      return fileData.toString();‍‍‍‍‍‍‍‍‍‍‍‍‍

davtrasher
Champ in-the-making
Champ in-the-making
I try an other way to do my upload:

public String uploadDocs(String title, String description, String correspondant,String nodeid){      HttpURLConnection conn = null;      BufferedReader br = null;      DataOutputStream dos = null;      DataInputStream inStream = null;      InputStream is = null;      OutputStream os = null;      boolean ret = false;      String StrMessage = "";      String exsistingFileName = "D:\\Docs_scannes\\PDF\\advanced-workflow-article.pdf";      String lineEnd = "\r\n";      String twoHyphens = "–";      String boundary =  "*****";      int bytesRead, bytesAvailable, bufferSize;      byte[] buffer;      int maxBufferSize = 1*1024*1024;      String responseFromServer = "";      String urlString = "http://localhost:8082/alfresco/wcservice/sample/uploadNew";      try      {         //—————— CLIENT REQUEST         FileInputStream fileInputStream = new FileInputStream( new               File(exsistingFileName) );         // open a URL connection to the Servlet          URL url = new URL(urlString);         // Open a HTTP connection to the URL         conn = (HttpURLConnection) url.openConnection();         // Allow Inputs         conn.setDoInput(true);         // Allow Outputs         conn.setDoOutput(true);         // Don't use a cached copy.         conn.setUseCaches(false);         // Use a post method.         conn.setRequestMethod("POST");         conn.setRequestProperty("Connection", "Keep-Alive");                      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);         dos = new DataOutputStream( conn.getOutputStream() );         dos.writeBytes(twoHyphens + boundary + lineEnd);         dos.writeBytes("Content-Disposition: form-data; name=\"nodeid\"" + lineEnd + lineEnd);         System.out.println(nodeid + lineEnd);         dos.writeBytes( nodeid + lineEnd);         dos.writeBytes(twoHyphens + boundary + lineEnd);         dos.writeBytes("Content-Disposition: form-data; name=\"file\";"               + " filename=\"" + exsistingFileName +"\"" + lineEnd);         dos.writeBytes(lineEnd);          dos.writeBytes(twoHyphens + boundary + lineEnd);                  dos.writeBytes("Content-Disposition: form-data; name=\"title\"" + lineEnd + lineEnd);         dos.writeBytes( title + lineEnd);         System.out.println(title + lineEnd);         dos.writeBytes(twoHyphens + boundary + lineEnd);         dos.writeBytes("Content-Disposition: form-data; name=\"desc\"" + lineEnd + lineEnd);         dos.writeBytes( description + lineEnd);         dos.writeBytes(twoHyphens + boundary + lineEnd);         dos.writeBytes("Content-Disposition: form-data; name=\"author\"" + lineEnd + lineEnd);         dos.writeBytes( correspondant + lineEnd);         dos.writeBytes(twoHyphens + boundary + lineEnd);         dos.writeBytes("Content-Disposition: form-data; name=\"ticket\"" + lineEnd + lineEnd);         dos.writeBytes( getTicket() + lineEnd);         // create a buffer of maximum size         bytesAvailable = fileInputStream.available();         bufferSize = Math.min(bytesAvailable, maxBufferSize);         buffer = new byte[bufferSize];         // read file and write it into form…         bytesRead = fileInputStream.read(buffer, 0, bufferSize);         while (bytesRead > 0)         {            dos.write(buffer, 0, bufferSize);            bytesAvailable = fileInputStream.available();            bufferSize = Math.min(bytesAvailable, maxBufferSize);            bytesRead = fileInputStream.read(buffer, 0, bufferSize);         }         // send multipart form data necesssary after file data…         dos.writeBytes(lineEnd);         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);         // close streams         fileInputStream.close();         dos.flush();         dos.close();      }      catch (MalformedURLException ex)      {         System.out.println("From ServletCom CLIENT REQUEST:"+ex);      }      catch (IOException ioe)      {         System.out.println("From ServletCom CLIENT REQUEST:"+ioe);      }      //—————— read the SERVER RESPONSE      try      {         inStream = new DataInputStream ( conn.getInputStream() );         String str;         while (( str = inStream.readUTF()) != null)         {            System.out.println("Server response is: "+str);            System.out.println("");         }         inStream.close();      }      catch (IOException ioex)      {         System.out.println("From (ServerResponse): "+ioex);      }      return urlString;   }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
the upload web script:
// get folder to upload into with nodeidif ((args.nodeid) && (args.nodeid != "")){   model.folder = search.findNode("workspace://SpacesStore/" + args.nodeid);}var filename = null;var content = null;var mimetype = null;encoding = null;var title = null;var description = null;var author = null;var name = null;// locate file attributesfor each (field in formdata.fields){   if (field.name == "title")   {      title = field.value;   }   else if (field.name == "desc")   {      description = field.value;   }   else if (field.name == "author")   {      author = field.value;   }   else if (field.name == "name")   {      // for having name properties different than original filename      name = field.value;   }   else if (field.name == "file" && field.isFile)   {      filename = field.filename;      content = field.content;      encoding = "UTF-8";   }}if ((args.mimetype) &&  (args.mimetype != "")){   mimetype = args.mimetype;}// ensure folder and mandatory file attributes have been locatedif (model.folder == null || filename == undefined || content == undefined){  status.code = 400;  status.message = "Uploaded file cannot be located in request";  status.redirect = true;}else{  // create document in model.folder for uploaded file  upload = model.folder.createFile("upload" + model.folder.children.length + "_" + filename);  upload.properties.content.write(content);  upload.properties.content.encoding = encoding;  upload.properties.content.mimetype = mimetype;  if (name != null)  {     upload.properties.name = name;   }  else  {     upload.properties.name = filename;  }  if (title != null)  {     upload.properties.title = title;  }  if (description != null)  {     upload.properties.description = description;  }  if (author != null)  {     upload.properties.author = author;  }    upload.save();  // setup model for response template  model.upload = upload;}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Now, in the response provided by the server, I've got the alfresco "loginform", there is a problem of authentication, however, I pass the ticket in the outputstream …

risenhoover
Champ in-the-making
Champ in-the-making
Here's an interesting post on the AlfrescoForge FlexSpaces+AIR forum.  It's the same "cannot upload" issue…

http://forge.alfresco.com/forum/message.php?msg_id=1486


Hi all,

The issue had to do with the "args" object being used to retrieve the destination folder path and mimetype. An example post is found below. In the uploadNew.post.js script, model.folder would end up null because this code would not execute:

else if ((args.path) && (args.path != ""))
{
// get folder to upload into with doc mgt path
model.folder = roothome.childByNamePath(args.path);
}

The solution was to get all parameters from the formdata and not use args:

——–
else if (field.name == "path")
{
path = field.value;
}
else if (field.name == "mimetype")
{
mimetype = field.value;
}
}
model.folder = roothome.childByNamePath(path);
———-

I am guessing that this is due to API changes, as the FlexSpaces 0.5 build was giving the same error out-of-box.

Thanks,
John

davtrasher
Champ in-the-making
Champ in-the-making
I solved the problem of authentication, I had to pass the ticket directly in the url and not in the ouputstream. Now I've got a new error to the end of the webscript in the instruction: upload.save():
Caught exception & redirecting to status template:jdbc exception on Hibernate data access; nested exception is org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update

davtrasher
Champ in-the-making
Champ in-the-making
I can upload text and binary files to alfresco with a simple html form, I can upload text files with the method of the first post on this topic. But impossible to upload a binary file with the 2nd method because the content is null, obviously it can not find the field.content … I don't know what to do!

lakshya
Champ in-the-making
Champ in-the-making
Did u get the solution to upload binary files in Alfresco through REStful API.

I am using  webscript upload.post.desc.xml

<webscript>  <shortname>File Upload</shortname>  <description>Upload file content and meta-data into Repository</description>  <url>/api/upload</url>  <format default="json"/>  <authentication>user</authentication>  <transaction>required</transaction></webscript>‍‍‍‍‍‍‍‍
and

upload.post.js
    // get folder to upload into with nodeid    if ((args.nodeid) && (args.nodeid != ""))    {       model.folder = search.findNode("workspace://SpacesStore/" + args.nodeid);    }    var filename = null;    var content = null;    var mimetype = null;    encoding = null;    var title = null;    var description = null;    var author = null;    var name = null;    // locate file attributes    for each (field in formdata.fields)    {       if (field.name == "title")       {          title = field.value;       }       else if (field.name == "desc")       {          description = field.value;       }       else if (field.name == "author")       {          author = field.value;       }       else if (field.name == "name")       {          // for having name properties different than original filename          name = field.value;       }       else if (field.name == "file" && field.isFile)       {          filename = field.filename;          content = field.content;          encoding = "UTF-8";       }    }    if ((args.mimetype) &&  (args.mimetype != ""))    {       mimetype = args.mimetype;    }    // ensure folder and mandatory file attributes have been located    if (model.folder == null || filename == undefined || content == undefined)    {      status.code = 400;      status.message = "Uploaded file cannot be located in request";      status.redirect = true;    }    else    {      // create document in model.folder for uploaded file      upload = model.folder.createFile("upload" + model.folder.children.length + "_" + filename);      upload.properties.content.write(content);      upload.properties.content.encoding = encoding;      upload.properties.content.mimetype = mimetype;      if (name != null)      {         upload.properties.name = name;      }      else      {         upload.properties.name = filename;      }      if (title != null)      {         upload.properties.title = title;      }      if (description != null)      {         upload.properties.description = description;      }      if (author != null)      {         upload.properties.author = author;      }           upload.save();      // setup model for response template      model.upload = upload;    }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

My java code is :
public static String uploadDocs(String title, String description, String correspondant,String nodeid){        HttpURLConnection conn = null;        BufferedReader br = null;        DataOutputStream dos = null;        DataInputStream inStream = null;        InputStream is = null;        OutputStream os = null;        boolean ret = false;        String StrMessage = "";        String exsistingFileName = "C:/Uploads/Alfresco2_1_Installation_Guide.pdf";        String lineEnd = "\r\n";        String twoHyphens = "–";        String boundary =  "*****";        int bytesRead, bytesAvailable, bufferSize;        byte[] buffer;        int maxBufferSize = 1*1024*1024;        String responseFromServer = "";        String urlString = "http://localhost:8081/alfresco/service/api/upload";        //String urlString = "http://localhost:8081/alfresco/service/api/path/workspace/SpacesStore/Company%20Home/children";        try        {           //—————— CLIENT REQUEST           FileInputStream fileInputStream = new FileInputStream( new                 File(exsistingFileName) );           // open a URL connection to the Servlet           URL url = new URL(urlString);           // Open a HTTP connection to the URL           conn = (HttpURLConnection) url.openConnection();           // Allow Inputs           conn.setDoInput(true);           // Allow Outputs           conn.setDoOutput(true);           // Don't use a cached copy.           conn.setUseCaches(false);           // Use a post method.           conn.setRequestMethod("POST");                      BASE64Encoder enc = new sun.misc.BASE64Encoder();           String userpassword = "admin" + ":" + "admin";           String encodedAuthorization = enc.encode( userpassword.getBytes() );           conn.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);                      conn.setRequestProperty("Connection", "Keep-Alive");                        conn.setRequestProperty("Content-Type", "multipart/form-data");           dos = new DataOutputStream( conn.getOutputStream() );           dos.writeBytes(twoHyphens + boundary + lineEnd);           dos.writeBytes("Content-Disposition: form-data; name=\"nodeid\"" + lineEnd + lineEnd);           System.out.println(nodeid + lineEnd);           dos.writeBytes( nodeid + lineEnd);           dos.writeBytes(twoHyphens + boundary + lineEnd);           dos.writeBytes("Content-Disposition: form-data; name=\"file\";"                 + " filename=\"" + exsistingFileName +"\"" + lineEnd);           dos.writeBytes(lineEnd);           dos.writeBytes(twoHyphens + boundary + lineEnd);                   dos.writeBytes("Content-Disposition: form-data; name=\"title\"" + lineEnd + lineEnd);           dos.writeBytes( title + lineEnd);           System.out.println(title + lineEnd);           dos.writeBytes(twoHyphens + boundary + lineEnd);           dos.writeBytes("Content-Disposition: form-data; name=\"desc\"" + lineEnd + lineEnd);           dos.writeBytes( description + lineEnd);           dos.writeBytes(twoHyphens + boundary + lineEnd);           dos.writeBytes("Content-Disposition: form-data; name=\"author\"" + lineEnd + lineEnd);           dos.writeBytes( correspondant + lineEnd);           dos.writeBytes(twoHyphens + boundary + lineEnd);           dos.writeBytes("Content-Disposition: form-data; name=\"ticket\"" + lineEnd + lineEnd);           //dos.writeBytes( "TICKET_537919ac00417ec3f87e1801e5ede28315845f39" + lineEnd);                      // create a buffer of maximum size           bytesAvailable = fileInputStream.available();           bufferSize = Math.min(bytesAvailable, maxBufferSize);           buffer = new byte[bufferSize];                      // read file and write it into form…           bytesRead = fileInputStream.read(buffer, 0, bufferSize);           while (bytesRead > 0)           {              dos.write(buffer, 0, bufferSize);              bytesAvailable = fileInputStream.available();              bufferSize = Math.min(bytesAvailable, maxBufferSize);              bytesRead = fileInputStream.read(buffer, 0, bufferSize);           }                      // send multipart form data necesssary after file data…           dos.writeBytes(lineEnd);           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);           // close streams           fileInputStream.close();           dos.flush();           dos.close();        }        catch (MalformedURLException ex)        {           System.out.println("From ServletCom CLIENT REQUEST:"+ex);        }        catch (IOException ioe)        {           System.out.println("From ServletCom CLIENT REQUEST:"+ioe);        }        //—————— read the SERVER RESPONSE        try        {           inStream = new DataInputStream ( conn.getInputStream() );           String str;           while (( str = inStream.readUTF()) != null)           {              System.out.println("Server response is: "+str);              System.out.println("");           }           inStream.close();        }        catch (IOException ioex)        {           System.out.println("From (ServerResponse): "+ioex);        }        return urlString;     }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I am getting the following error while running


From (ServerResponse): java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8081/alfresco/service/api/upload
http://localhost:8081/alfresco/service/api/upload

Can you help me. how did you uploaded binary file in alfresco

ghm1014
Champ in-the-making
Champ in-the-making
Hi

I uploaded binary data but somehow the content is corrupted, even the size is different (almost double of original size), however text content is ok. Here is my code:

… for each (field in formdata.fields)  {      if (field.isFile){                  node.properties.content.encoding="UTF-8";         node.properties.content.guessMimetype(field.value);         node.content=field.content.getContent();              }  }…node.save();‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I guess I have some problems with the encoding or decoding of the binary file. The write() method never works for me.

Thanks

ghm1014
Champ in-the-making
Champ in-the-making
I found how to upload binary file, I hope this help.

    …    for each (field in formdata.fields)      {          if (field.isFile){                      node.properties.content.encoding="UTF-8";             node.properties.content.guessMimetype(field.value);             node.properties.content.write(field.content.getInputStream());         }      }    …    node.save();‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

krithika123
Champ in-the-making
Champ in-the-making
Hi,
for each (field in formdata.fields)

      {

          if (field.isFile){        
             node.properties.content.encoding="UTF-8";
             node.properties.content.guessMimetype(field.value);
             node.properties.content.write(field.content.getInputStream());
         }

      }

I tried uploading a file through jscript using the guessMimetype(field.value) but the result am getting is undefined

My upload.js is as
var fileMimeType = docNode.properties.content.guessMimetype(filename); logger.log(" fileMimeType  is ::: "+fileMimeType);‍‍‍‍‍

The output on enabling the log is :
fileMimeType  is :::  undefined‍‍‍

Can u tell me where i am going wrong because only the mimetype is undefined though the filename comes perfect.
Please help !!!!