Thursday 22 December 2011

Upload file to SharePoint site

Upload file to SharePoint site
This task use Java WSDL for SharePoint to upload file to SharePoint site.
Upload file to SharePoint site using Copy webservice
Call uploadFile. site argument contains domain name instead of IP.
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;
}
    

 

No comments:

Post a Comment