How to put a binary file inside POST form data paramaters in Java

81 views Asked by At

I am attempting to upload an image to the Mastodon API and that requires me to make a form with "file=(binary)"

This Java code does not work as expected and returns "500" instead meaning the server cannot process the image. Am I doing something wrong here? Here's the relevant code snippet:

    public int uploadImage(Path imageLocation) throws MalformedURLException, IOException {
        int imageID = 0;
        try {
            HttpURLConnection connection = (HttpsURLConnection) new URL("https", instanceURL, "/api/v2/media").openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data");
            connection.setRequestProperty("Authorization", "Bearer " + accessToken);
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes("file=" + Files.readAllBytes(imageLocation));
            imageID = connection.getResponseCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageID;
    }

I tried doing this in cURL to good success, but I'm unsure why the Java code does not work.

curl \
-X POST \
-H "Authorization: Bearer [hidden]" \
-H "Content-Type: multipart/form-data" \
--form "file=@${FILE_LOC}" \
https://mstdn.plus.st/api/v2/media

Can anyone help me out here? Thanks.

0

There are 0 answers