Java の追加パラメータを使用した HTTP サーバーへのファイルのアップロード
HTTP サーバーへのファイルのアップロードは、多くのアプリケーションで一般的に必要です。ただし、場合によっては、ファイルと一緒に追加のパラメーターを渡すことも必要になります。外部ライブラリを使用せずにファイルとパラメータの両方を送信できるソリューションは次のとおりです。
java.net.URLConnection と Multipart/Form-Data
ファイルを送信するには、パラメータを使用するには、java.net.URLConnection を利用し、multipart/form-data エンコーディングを使用します。マルチパート/フォームデータを使用すると、単一の HTTP リクエストでバイナリ データ (ファイル) と文字データ (パラメータ) を混在させることができます。
コード例:
String url = "http://example.com/upload";
String charset = "UTF-8";
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());
String CRLF = "\r\n";
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);
) {
// Send normal param.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" textFile.getName() "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// Send binary file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" binaryFile.getName() "\"").append(CRLF);
writer.append("Content-Type: " URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// 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 = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
追加の注意:
参照:
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3