जावा में अतिरिक्त पैरामीटर्स के साथ HTTP सर्वर पर फ़ाइलें अपलोड करना
HTTP सर्वर पर फ़ाइलें अपलोड करना कई अनुप्रयोगों के लिए एक सामान्य आवश्यकता है। हालाँकि, कभी-कभी फ़ाइलों के साथ अतिरिक्त पैरामीटर पास करना भी आवश्यक होता है। यहां एक समाधान है जो आपको बाहरी पुस्तकालयों का उपयोग किए बिना फ़ाइलें और पैरामीटर दोनों भेजने की अनुमति देता है:
java.net.URLConnection और Multipart/Form-Data
फ़ाइलें भेजने के लिए और पैरामीटर, आप java.net.URLConnection का उपयोग करेंगे और मल्टीपार्ट/फॉर्म-डेटा एन्कोडिंग का उपयोग करेंगे। मल्टीपार्ट/फॉर्म-डेटा आपको एक ही 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