Sample code for 30+ languages & platforms
Java

Set a Multipart Part Body from a Stream

See more REST Examples

Demonstrates Rest.SetMultipartBodyStream, which uses a Stream as the body source for the selected multipart part.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. Streaming a part body is appropriate for large parts because the data is read incrementally from the source rather than being buffered entirely in memory. The part is otherwise assembled the same way — select the part, set its headers, then set its body.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Stream;

public class ChilkatExample {

    public static void main(String[] args) {
        Rest rest = new Rest();
        boolean bTls = true;
        boolean bAutoReconnect = true;
        try {
            rest.connect("example.com", 443, bTls, bAutoReconnect);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The file paths are relative to the application's current working directory.  Absolute paths
        // may also be used.  Supply the paths appropriate to your own environment.

        // Select the multipart part to build, and set its header fields.
        rest.setPartSelector("1");
        rest.addHeader("Content-Disposition", "form-data; name=\"field1\"");
        rest.addHeader("Content-Type", "application/octet-stream");

        // Use a Stream as the body source for the selected part.  The stream's source is a local file,
        // which is appropriate for large parts.
        Stream partStream = new Stream();
        partStream.setSourceFile("qa_data/attachment.bin");
        String responseText;
        try {
            rest.setMultipartBodyStream(partStream);

            responseText = rest.fullRequestMultipart("POST", "/api/upload");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(responseText);
    }
}