멀티 파트 파일 업로드를 허용하는 웹 서버에 이미지를 업로드하는 프로그램을 만들려고합니다.자바에서 다중 파트 파일 업로드 게시 요청
더 구체적으로 "pic"변수로 파일을 보내는 http://iqs.me에 http POST 요청을 보내려고합니다.
많은 시도를 해봤지만 가까운지 알 수 없습니다. 가장 어려운 부분은 HttpURLConnection을 사용하여 POST 유형을 요청하는 것입니다. 내가 얻는 반응은 GET을 만드는 것처럼 보입니다.
(그리고 내가 제 3 자 libs가없이이 작업을 수행 할 수)
업데이트 : 비 작동 코드가 여기에 표시됩니다 (오류없이하지만 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);
}
을 업로드이 사용하고 발견 ... –
좋아 코드 : – Martin
그렇게하지를 추가 지금 당장이 모든 것을 처리 할 시간이 있지만 작업 코드 샘플로 답변을 게시 한 후에도 유용 할 수 있습니다. [here] (http://stackoverflow.com/questions/2469451/upload- 파일 -와 - 자바/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