java post 文件上传_JAVA POST 上传文件

public String upload(String url, ArrayList 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

大神们,我这代码问题出在哪

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值