public String upload(String url, ArrayList<File> files) { String BOUNDARY = "------WebKitFormBoundary"; //数据分隔线 String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志 StringBuilder sb = new StringBuilder(); HttpURLConnection http = null; BufferedReader in = null; DataOutputStream out = null; try { URL u = new URL(url); http = (HttpURLConnection) u.openConnection(); http.setRequestMethod("POST"); http.setDoOutput(true); http.setRequestProperty("Charset", charset); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"); http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); http.setConnectTimeout(ConnectTimeout); http.setReadTimeout(ReadTimeout); http.connect(); out = new DataOutputStream(http.getOutputStream()); for (File file : files) { String fileBody = endline + "Content-Disposition: form-data;name=\"Filedata\";filename=\"" + file.getName() + "\"\r\n"; fileBody += "Content-Type: image/jpeg\r\n\r\n"; System.out.println(fileBody); out.write(fileBody.getBytes()); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer, 0, 1024)) != -1) { out.write(buffer, 0, len); } out.write("\r\n".getBytes()); } String postBody = endline + "Content-Disposition: form-data;name=\"test\"\r\n\r\n11\r\n"; System.out.println(postBody); out.write(postBody.getBytes()); out.write(endline.getBytes()); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader(http.getInputStream(), charset)); String tmp; while ((tmp = in.readLine()) != null) { sb.append(tmp).append("\n"); } in.close(); } catch (Exception ex) { Logger.getLogger(Http.class.getName()).log(Level.SEVERE, null, ex); } finally { close(http, in, out); return sb.toString(); } }
PHP 页面
print_r($_FILES);
print_r($_POST);
upload 返回的结果是空 array
不要让我去用httpclient
大神们,我这代码问题出在哪
没法直接传文件流吧,需要转换成Base64吧