Upload Object

The SDK methods listed in this section will allow you to upload objects to the bucket in various manners. You can upload objects as a string or as a stream. The Bucket reference used in the below code snippet is the component instance.

If you do not have Versioning enabled for your object, and if Stratus gets multiple write requests for the same object, the object will be continuously overwritten. The latest upload of the object will be the only object that is stored.

However, with Versioning enabled, each upload will be considered a version of the object, and all of them will be stored in the bucket, each with a unique versionId.

Note: The following characters including space are not supported when you create a path or an object: double quote, both angular brackets, hashtag, backward slash and pipe symbol.

Upload Object as a Stream

Using this SDK method, you can upload objects to a bucket as a stream. Store the stream in a variable and then pass that variable in the upload method.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCPutObjectOptions; import java.nio.file.Path; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.io.*;
    
copy
InputStream file =new FileInputStream("filePath"); Boolean res = bucket.putObject("sam/out/sample.txt", file); System.out.println(res);

Upload Object as a String

Using this SDK method, you can upload the object as a string. You will pass the object name, and the data to be stored in the object in string format in the upload method; putObject()

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCPutObjectOptions; import java.nio.file.Path; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.io.*;
    
copy
Boolean res = bucket.putObject("sam/out/sample.txt", "content of the file"); System.out.println(res);

Upload Object with Options

Using this SDK method, you can use the following options while you upload an object.

  • setOverwrite(): This is an option you can use, if Versioning for your bucket is not enabled for your bucket. Without versioning, you need to use this option if you wish to overwrite a resource. The default value is ‘false’.

  • setTTL(): This is an option you can use to set Time-to-Live (TTL) in seconds for an object. Value should be greater than or equal to 60 seconds.

  • setMetaData(): This is an option you can use to upload meta details of the object that is being uploaded.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCPutObjectOptions; import java.nio.file.Path; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Map; import java.io.*;
    
copy
ZCPutObjectOptions options = ZCPutObjectOptions.getInstance(); options.setTTL("1000"); options.setOverwrite("true"); Map<String, String> metaData = new HashMap<String, String>(); metaData.put("author", "John"); options.setMetaData(metaData); InputStream file = new FileInputStream("filePath"); Boolean res = bucket.putObject("sam/out/sample.txt", file, options); System.out.println(res);

Upload an Object Using Multipart Operations

When the Object that you need to upload is too large to upload, you can perform a multipart operation. The multipart operation will split the object into multiple parts and perform a quicker upload. In this SDK section, we are going to go over all the SDK methods that are available to perform multipart upload of objects in Stratus.

Initiate Multipart Upload

Using the following SDK method, we are going to return a uploadId. This ID will allow us to upload multiple pats of the object.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCInitiateMultipartUpload;
    
copy
ZCInitiateMultipartUpload multipart = bucket.initiateMultipartUpload("sam/out/sample.txt");

Perform Multipart Upload for Parts of the Object

In the following SDK method, we are going to perform uploads of the individual parts of the object. Each part will have a distinct part_number ranging anywhere between 1 and 1000. While this represents the ordering of the parts, these parts will not necessarily be uploaded in sequence. These parts will be combined in sequence once the upload of all the parts of the objects is complete.

Parameters Used

Parameter Name Data Type Definition
key String A Mandatory parameter. Will hold the name of the object.
uploadId String A Mandatory parameter. This value is returned in the Initiate Multipart Upload method.
part InputStream A Mandatory parameter. Will hold the data of the object part.
partNumber Int A Mandatory parameter. Will have the ordering of the parts that are being uploaded.

Ensure the following packages are imported

    
copy
import java.io.*;
    
copy
int partNumber = 1; InputStream part = new FileInputStream("filePath"); Boolean res = bucket.uploadPart("sam/out/sample.txt", "uploadId", part, partNumber); System.out.println(res);

Get Multipart Upload Summary

The following SDK method can be used to obtain an operational summary of all the uploaded parts. To view the summary, we pass the uploadId to the getMultipartUploadSummary() method.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCMultipartObjectSummary;
    
copy
ZCMultipartObjectSummary summaryRes = bucket.getMultipartUploadSummary("sam/out/sample.txt", "uploadId"); // accessing uploaded parts System.out.println("Object Name:" + summaryRes.getKey()); System.out.println("Upload Id:" + summaryRes.getUploadId()); System.out.println("Status:" + summaryRes.getStatus()); System.out.println(summaryRes.getParts().get(0).getUploadedAt()); System.out.println(summaryRes.getParts().get(0).getPartNumber());

Complete Multipart Upload Operation

The following method allows us to terminate the multipart process once all the parts have been successfully uploaded. To complete the process we will pass the uploadId to the completeMultipartUpload() method.

    
copy
Boolean completeRes = bucket.completeMultipartUpload("sam/out/sample.txt", "uploadId"); System.out.println(completeRes);

Example Snippet Illustring Implementation of Multipart Operations

Ensure the following packages are imported

    
copy
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger; import java.util.logging.Level; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.catalyst.advanced.CatalystAdvancedIOHandler; import com.zc.component.stratus.ZCBucket; import com.zc.component.stratus.ZCStratus; import com.zc.component.stratus.beans.ZCInitiateMultipartUpload; import com.zc.exception.ZCServerException; import java.io.InputStream; import java.io.FileInputStream; import java.io.ByteArrayInputStream;
    
copy
public class MultipartUpload implements CatalystAdvancedIOHandler { private static final Logger LOGGER = Logger.getLogger(Sample.class.getName()); @Override public void runner(HttpServletRequest request, HttpServletResponse response) throws Exception { try { switch (request.getRequestURI()) { case "/": { ZCStratus stratus = ZCStratus.getInstance(); // get bucket instance ZCBucket bucket = stratus.bucketInstance("sample"); // multipart upload String key = "sample.mp4"; InputStream file = new FileInputStream( "/users/sam/sample.mp4"); ZCInitiateMultipartUpload initiateUploadResponse = bucket.initiateMultipartUpload(key); String uploadId = initiateUploadResponse.getUploadId(); System.out.println("Multipart upload initiated. Upload ID: " + uploadId); // File size and part size (50 MB minimum) int partSize = 50 * 1024 * 1024; // 50 MB long fileSize = file.available(); double result = (double) fileSize / partSize; int noOfParts = (int) Math.ceil(result); // Upload parts in parallel List<CompletableFuture<Void>> uploadedParts = new ArrayList<>(); ExecutorService executor = Executors.newFixedThreadPool(4); int partNumber = 1; while (noOfParts >= partNumber) { int currentPartNumber = partNumber; byte[] buffer = new byte[partSize]; file.read(buffer); InputStream fileData = new ByteArrayInputStream(buffer); uploadedParts.add(CompletableFuture.runAsync(() -> { try { bucket.uploadPart(key, uploadId, fileData, currentPartNumber); LOGGER.log(Level.INFO, "Part {0} Uploaded", currentPartNumber); } catch (Exception e) { throw new RuntimeException(e); } }, executor)); partNumber++; } CompletableFuture<Void> isUploaded = CompletableFuture .allOf(uploadedParts.toArray(new CompletableFuture[0])); try { isUploaded.get(); } catch (Exception e) { throw new ZCServerException("Error while uploading the object", e); } Boolean completeRes = bucket.completeMultipartUpload(key, uploadId); if (completeRes) { LOGGER.log(Level.INFO, "Upload Completed"); } } default: { response.setStatus(404); response.getWriter().write("You might find the page you are looking for at \"/\" path"); } } } catch (Exception e) { if (e instanceof ZCServerException) { int statusCode = ((ZCServerException) e).getStatus(); System.out.println("HTTP status code: " + statusCode); } LOGGER.log(Level.SEVERE, "Exception in Sample", e); } } }

Upload an Object Using Transfer Manager

Create Transfer Manager Instance

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.transfer.ZCTransferManager;
    
copy
ZCTransferManager transferManager= ZCTransferManager.getInstance(bucket);

Multipart Upload

Create Multipart Upload Instance

The following SDK method will create a multipart instance by initiating multipart upload.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCMultipartUpload;
    
copy
ZCMultipartUpload multipart = transferManager.createMultipartInstance("sam/out/sample.txt");

If you are required to create an instance for an already initialized multipart upload operation, then copy and use the code snippet given below

    
copy
ZCMultipartUpload multipart = transferManager.createMultipartInstance("sam/out/sample.txt", "uploadId");

Upload Part

In the following SDK method we are going to be using the multipart instance we initalized in the Create Multipart Upload Instance section.

Ensure the following packages are imported

    
copy
import java.io.InputStream;
    
copy
int partNumber = 1; InputStream part = new FileInputStream("filePath"); Boolean uploadRes = multipart.uploadPart(part, partNumber); System.out.println(uploadRes);

Upload Summary

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.beans.ZCMultipartObjectSummary;
    
copy
ZCMultipartObjectSummary summaryRes = multipart.getUploadSummary(); // accessing uploaded parts System.out.println("Object Name:" + summaryRes.getKey()); System.out.println("Upload Id:" + summaryRes.getUploadId()); System.out.println("Status:" + summaryRes.getStatus()); System.out.println(summaryRes.getParts().get(0).getUploadedAt()); System.out.println(summaryRes.getParts().get(0).getPartNumber()); System.out.println(summaryRes.getParts().get(0).getSize());

Complete Upload

    
copy
Boolean completeRes = multipart.completeUpload(); System.out.println(completeRes);

Upload Object Using Wrapper

The following SDK method acts as a wrapper, where the entire multipart upload operation is carried out without employing multiple steps. Using this method, the object is split into multiple parts, uploaded to the bucket in multiple parts, and then combined once all the parts are uploaded.

    
copy
import java.io.InputStream; import com.zc.component.stratus.beans.ZCMultipartObjectSummary;
    
copy
InputStream file =new FileInputStream("filePath"); int partSize = 50; ZCMultipartObjectSummary res = transferManager.putObjectAsParts("objetName", file, partSize);
Note: For object's that are larger than 2GB, we would recommend that you use the individual SDK methods to carry out the multipart upload operation successfully.

Generate Presigned URL to Upload an Object

Presigned URLs are secure URLs that authenticated users can share to their non-authenticated users. This URL will provide non-authenticated users with temporary authorization to access objects. The Bucket reference used in the below code snippet is the component instance.

Info: To use this SDK method, you need intialize it with Admin scope. You can learn more about this requirement from this section

Parameters Used

Parameter Name Data Type Definition
key String A Mandatory parameter. Will hold the complete name of the object along with it's path.
URL_ACTION Enum A Mandatory parameter. This is the parameter that will allow you to generate a presigned URL for an upload action.
  • URL_ACTION.PUT: To upload an object
expiry String This is an Optional parameter. The URL validity time in seconds.
  • Default value: 3600 seconds
  • Minimum value: 30 seconds
  • Maximum value: 7 days
activeFrom String This is an Optional parameter. This param will contain the time after which the URL is valid. Maximum value is 7 days. URLs are made active as soon as they are generated by default.

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.enums.URL_ACTION; import org.json.simple.JSONObject;
    
copy
JSONObject res = bucket.generatePreSignedUrl("sam/out/sample.txt", URL_ACTION.PUT); System.out.println(res.get("signature"));

Generate Presigned URL With Expiry and Active Time

Ensure the following packages are imported

    
copy
import com.zc.component.stratus.enums.URL_ACTION; import org.json.simple.JSONObject;
    
copy
JSONObject res = bucket.generatePreSignedUrl("object_name",URL_ACTION.GET, "expiry_in","active_from"); System.out.println(res.get("signature"));

Example Response for Generating a Presigned URL for Upload

    
copy
{ "signature": "https://sadi-development.zohostratus.com/_signed/sam.txt?organizationId=96862383&stsCredential=96858154-96862383&stsDate=1747904989454&stsExpiresAfter=300&stsSignedHeaders=host&stsSignature=UPyH5A4AdAaCpw6S6jVhKFSxg3B0B0p619YN0cAIn4c", "expiry_in_seconds": "100", "active_from": "1726492859577" }

Example Snippet Illustrating Usage of Presigned URL to Upload an Object

    
copy
import okhttp3.*; import java.io.File; import java.io.IOException; public class BinaryFileUpload { public static void main(String[] args) throws IOException { // Create an OkHttpClient instance for making HTTP requests OkHttpClient client = new OkHttpClient(); // Specify the file to upload — replace "file_path" with actual file location File file = new File("file_path"); // Create the request body with binary content (octet-stream) RequestBody requestBody = RequestBody.create( MediaType.parse("application/octet-stream"), // Use a specific MIME type if known file ); // ️ Build the PUT request with the pre-signed URL Request request = new Request.Builder() .url("https://sadi-development.zohostratus.com/_signed/sam.txt?organizationId=96862383&stsCredential=96858154-96862383&stsDate=1747904989454&stsExpiresAfter=300&stsSignedHeaders=host&stsSignature=UPyH5A4AdAaCpw6S6jVhKFSxg3B0B0p619YN0cAIn4c") // Replace with a actual URL .put(requestBody) // PUT request to upload file .build(); // Execute the request and handle the response try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { System.out.println("Object uploaded successfully"); } else { // Print error if upload fails System.err.println("Error: " + response.code() + " - " + response.body().string()); } } } }

Last Updated 2025-06-03 12:50:19 +0530 +0530