Friday, 14 October 2011

Upload file to SharePoint site

In order to upload file to SharePoint site, please use following code:

private String uploadFile(String site, String username, String password, String library, String filename) {
     String tag = "";
     try {
      CopySoapStub stub = SharePointWSDL.newCopy(new URL(site + "/_vti_bin/Copy.asmx"), new CopyLocator());
      stub.setUsername(username);
      stub.setPassword(password);

      String name = (new File(filename)).getName();
      String tagPath = site + "/" + library + "/" + name; 
      FieldInformation[] fis = new FieldInformation[1];
      UnsignedIntHolder uih = new UnsignedIntHolder(new UnsignedInt());
      CopyResultCollectionHolder crch = new CopyResultCollectionHolder(new CopyResult[] { new CopyResult() });

      fis[0] = new FieldInformation();
      fis[0].setInternalName("Title");
      fis[0].setDisplayName(name);
      fis[0].setType(FieldType.Text);
      fis[0].setValue(name);
       
      stub.copyIntoItems(tagPath, new String[] { tagPath }, fis, readFile(filename), uih, crch);
      boolean success = true;
      for (int i = 0; i < crch.value.length; i++) {
       if (CopyErrorCode._Success.equals(crch.value[i].getErrorCode().getValue())) continue;
       logger.error(crch.value[i].getErrorCode().getValue() + " : " + crch.value[i].getErrorMessage());
       logger.info(crch.value[i].getDestinationUrl());
       success = false;
      }
      if (success) {
          tag = tagPath;
      }
     } catch (Exception e) {
      logger.error("", e);
     }
     return tag;
    }
    
    private byte[] readFile(String filename) {
     File file = new File(filename);
     byte[] tag = new byte[0];
     try {
         tag = new byte[(int)file.length()];
         InputStream is = new FileInputStream(file);     
         int offset = 0;
            int numRead = 0;
            while (offset < tag.length && (numRead = is.read(tag, offset, tag.length - offset)) >= 0) {
                offset += numRead;
            }     
     } catch (Exception e) {
      logger.error("", e);
     }
     return tag;
    }

Above code use Java WSDL for SharePoint

You should use domain name in site URL instead of IP.

Using IP will cause error. Please checkout Get 'Object reference not set to an instance of an object' error when upload file to SharePoint

No comments:

Post a Comment