Sample code for 30+ languages & platforms
Java

REST File Upload (multipart/form-data)

See more REST Examples

Demonstrates how to upload a file using multipart/form-data.

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) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Rest rest = new Rest();

        // Connect to the HTTP server using TLS.
        boolean bTls = true;
        int port = 443;
        boolean bAutoReconnect = true;
        // Make sure to replace "www.chilkatsoft.com" with your domain..
        try {
            rest.connect("www.chilkatsoft.com", port, bTls, bAutoReconnect);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Stream fileStream = new Stream();
        fileStream.setSourceFile("qa_data/jpg/starfish.jpg");

        rest.addHeader("Content-Type", "multipart/form-data");

        rest.setPartSelector("1");
        rest.addHeader("Content-Type", "image/jpg");
        rest.addHeader("Content-Disposition", "form-data; name=\"filename\"; filename=\"starfish.jpg\"");
        rest.setMultipartBodyStream(fileStream);
        rest.setPartSelector("0");

        String responseBody;
        try {
            responseBody = rest.fullRequestMultipart("POST", "/the_uri_path_to_receive_the_upload");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        if (rest.getResponseStatusCode() != 200) {
            System.out.println("Received error response code: " + rest.getResponseStatusCode());
            return;
        }

        System.out.println("File uploaded");
    }
}