使用 HTTP 请求上传文件
将文件上传到 HTTP 服务器,同时提交其他参数、java.net.URLConnection 和 multipart/通常采用形式数据编码。以下是该过程的细分:
Multipart/Form-Data 编码
Multipart/form-data 专为组合二进制(例如文件)的 POST 请求而设计和字符数据(例如参数)。编码涉及将请求正文分为多个部分,每个部分以边界字符串开头。
示例代码
<code class="java">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); } }</code>
附加注释
以上是如何使用 java.net.URLConnection 和 multipart/form-data 编码上传带有附加参数的文件?的详细内容。更多信息请关注PHP中文网其他相关文章!