Uploading Files with HTTP Requests
To upload files to an HTTP server while also submitting additional parameters, java.net.URLConnection and multipart/form-data encoding are commonly employed. Here's a breakdown of the process:
Multipart/Form-Data Encoding
Multipart/form-data is designed for POST requests that combine both binary (e.g., files) and character data (e.g., parameters). The encoding involves dividing the request body into multiple parts, each prefaced with a boundary string.
Example Code
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileUpload {
public static void main(String[] args) throws Exception {
String url = "http://example.com/upload";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis());
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, StandardCharsets.UTF_8), true)) {
// Send parameter
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"param\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8).append("\r\n");
writer.append("\r\n").append(param).append("\r\n").flush();
// Send text file
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8).append("\r\n");
writer.append("\r\n").flush();
Files.copy(textFile.toPath(), output);
output.flush();
writer.append("\r\n").flush();
// Send binary file
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append("\r\n");
writer.append("Content-Transfer-Encoding: binary").append("\r\n");
writer.append("\r\n").flush();
Files.copy(binaryFile.toPath(), output);
output.flush();
writer.append("\r\n").flush();
// End of multipart/form-data
writer.append("--" + boundary + "--").append("\r\n").flush();
}
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}
Additional Notes
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3