」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?

如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?

發佈於2025-04-09
瀏覽:785

How to upload files with additional parameters using java.net.URLConnection and multipart/form-data encoding? 
使用http request

上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 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).編碼涉及將請求主體劃分為多個部分,每個部分都以邊界字符串。

args)拋出異常{ 字符串url =“ http://example.com/upload”; 字符串param =“ value”; 文件textfile = new file(“/path/to/file.txt”); 文件binaryfile =新文件(“/path/to/file.bin”); 字符串邊界= long.tohexstring(system.currentTimeMillis()); urlConnection Connection = new URL(url).openconnection(); connection.setDoOutput(true); connection.setRequestProperty(“ content-type”,“多部分/form-data; boundare =” boundare); 嘗試(outputStream輸出= Connection.getOutputStream(); printwriter writer = new printwriter(new UppoteStreamWriter(output,standardcharsets.utf_8),true)){ //發送參數 writer.append(“ - ”邊界).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(); //發送文本文件 writer.append(“ - ”邊界).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.flush(); writer.append(“ \ r \ n”)。 flush(); //發送二進製文件 writer.append(“ - ”邊界).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-insoding:binary”)。 append(“ \ r \ n”); writer.append(“ \ r \ n”)。 flush(); files.copy(binaryfile.topath(),輸出); output.flush(); writer.append(“ \ r \ n”)。 flush(); //多部分/form-data的結尾 writer.append(“ - ”邊界“ - ”)。 append(“ \ r \ n”)。 flush(); } int響應=((httpurlConnection)連接).getResponsecode(); system.out.println(“響應代碼:” wonsectecode); } }

Additional Notes

Apache Commons FileUpload is only required on the server-side for handling uploaded files.

java.net.URLConnection is preferred for firing HTTP requests without external dependencies.
For more information,請參閱java.net.urlconnection和multipart/form-data(rfc2388)上的文檔。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3