Home > Java > javaTutorial > body text

How to Upload Files with Additional Parameters from a Java Client Using `multipart/form-data` Encoding Without Third-Party Libraries?

Linda Hamilton
Release: 2024-10-25 05:39:29
Original
541 people have browsed it

How to Upload Files with Additional Parameters from a Java Client Using `multipart/form-data` Encoding Without Third-Party Libraries?

Uploading Files with Additional Parameters from Java Client to HTTP Server

In the pursuit of uploading files along with additional parameters from a Java client to an HTTP server, let's explore a scenario and its solution.

Imagine you want to pass a file and a parameter called "username" to a server. How would you achieve this using a POST request with multipart/form-data encoding?

To keep things straightforward, let's steer clear of third-party libraries and rely on Java's built-in tools.

<code class="java">import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;

public class HttpFileUploadWithParameters {

    private static final String BOUNDARY = Long.toHexString(System.currentTimeMillis());
    private static final String CRLF = "\r\n";
    private static final String CHARSET = "UTF-8";

    public static void main(String[] args) throws Exception {
        String url = "http://example.com/upload";

        File file = new File("/path/to/file.txt");
        String parameter = "value";

        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        try (OutputStream output = connection.getOutputStream();
             PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true)) {

            // Write parameter
            writer.append("--" + BOUNDARY).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"parameter\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
            writer.append(CRLF).append(parameter).append(CRLF).flush();

            // Write file
            writer.append("--" + BOUNDARY).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF);
            writer.append("Content-Type: application/octet-stream").append(CRLF);
            writer.append(CRLF).flush();
            Files.copy(file.toPath(), output);
            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

            // End of multipart/form-data.
            writer.append("--" + BOUNDARY + "--").append(CRLF).flush();
        }

        // Request is lazily fired whenever you need to obtain information about response.
        int responseCode = ((java.net.HttpURLConnection) connection).getResponseCode();
        System.out.println(responseCode); // Should be 200
    }
}</code>
Copy after login

The above is the detailed content of How to Upload Files with Additional Parameters from a Java Client Using `multipart/form-data` Encoding Without Third-Party Libraries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!