我正試圖製作一個程序,將圖像上傳到接受多部分文件上傳的網絡服務器。來自java的多部分文件上傳發布請求
更具體地說,我想發一個http POST請求到http://iqs.me,發送變量「pic」中的一個文件。
我做了很多嘗試,但我不知道我是否已經接近。最難的部分似乎是讓HttpURLConnection發出POST類型的請求。我得到的迴應看起來像是一個GET。
(我想這樣做沒有任何第三方庫)
UPDATE:非工作的代碼放在這裏(沒有錯誤,但似乎並沒有做一個POST):
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "myScreenShot.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://iqs.local.com/index.php";
try{
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex){
System.out.println("Error:"+ex);
}catch (IOException ioe){
System.out.println("Error:"+ioe);
}
try{
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null){
System.out.println(str);
}
inStream.close();
}catch (IOException ioex){
System.out.println("Error: "+ioex);
}
請發表您的代碼,否則我們很難幫你... – 2010-04-15 14:40:11
好的代碼添加:) – Martin 2010-04-15 14:51:55
我不現在有足夠的時間去處理所有這些問題,但是我之前已經發布了有效的代碼示例的答案,您可能會發現它也很有用:[here](http://stackoverflow.com/questions/2469451/upload- files-with-java/2469587#2469587)和一個後續[這裏](http://stackoverflow.com/questions/2477449/simple-stream-read-write-question-in-java/2478127#2478127)。爲了保持所有的冗長和簡化所有的工作,我強烈建議繼續[Apache HttpComponents HttpClient](http://hc.apache.org/httpcomponents-client/index.html)。 – BalusC 2010-04-15 14:58:54