我正试图制作一个程序,将图像上传到接受多部分文件上传的网络服务器。来自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