Java Example of Uploading Files to a Library Item from a Local System
Last Updated December 16, 2024

This example shows how to upload an ISO image file from a local system to a library item.
This example uses the steps that are described in the Upload a File from a Local System to a Library Item procedure.
For related code samples, see the
vsphere-automation-sdk-java
VMware repository at GitHub.
...
 
// Access the com.vmware.content.library.item.updatesession.File.
// and the UpdateSession services by using the vSphere Automation Endpoint.
    File uploadFileService = this.vapiAuthHelper.getStubFactory().createStub(File.class, sessionStubconfig);
    UpdateSession uploadService= this.vapiAuthHelper.getStubFactory().createStub(UpdateSession.class, sessionStubconfig);

// Create an UpdateSessionModel instance to track the changes you make to the item.
    UpdateSessionModel updateSessionModel = new UpdateSessionModel();
    updateSessionModel.setLibraryItemId(newItem);

// Create a new update session.
    String clientToken = UUID.randomUUID().toString();
    String sessionId = uploadService.create(clientToken, updateSessionModel);

// Create an instance of the HttpClient class which is part of the 
// com.vmware.vcloud.suite.samples.common package.
    try {
       HttpClient httpClient = new HttpClient(true);

// Create a new AddSpec instance to describe the properties of the file to be uploaded.
       FileTypes.AddSpec fileSpec = new FileTypes.AddSpec();
       fileSpec.setName("ESXi patch");
       fileSpec.setSourceType(FileTypes.SourceType.PUSH);

// Link the ISO file specification to the update session.
       FileTypes.Info fileInfo = uploadFileService.add(sessionId, fileSpec);

// Use the HTTP library to upload the file to the library item.
       URI uploadUri = fileInfo.getUploadEndpoint().getUri();
       java.io.File file = new java.io.File("/updates/esxi/esxi_patch.iso");
       String transferUrl = uploadUri.toURL().toString();
       httpClient.upload(file, transferUrl);

// Mark the upload session as completed.
       uploadService.complete(sessionId);
    } finally {
         uploadService.delete(sessionId);
    }