java image写入文件_java-通过URLConnection写入图像

首先,我相信您应该在写入图像后调用io.flush(),然后再调用io.close().

第二内容类型对我来说似乎很奇怪.您似乎在尝试提交实际上是图像的表单.我不知道您的ASP期望什么,但是通常,当我编写应通过HTTP传输文件的代码时,我会发送适当的内容类型,例如图片/ jpeg.

例如,这是我从一个小实用程序中提取的代码片段,该小实用程序是我编写的并且在当前工作中正在使用:

URL url = new URL("http://localhost:8080/handler");

HttpURLConnection con = (HttpURLConnection)url.openConnection();

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

con.setRequestProperty("Content-Type", "image/jpeg");

con.setRequestMethod("POST");

InputStream in = new FileInputStream("c:/temp/poc/img/mytest2.jpg");

OutputStream out = con.getOutputStream();

copy(in, con.getOutputStream());

out.flush();

out.close();

BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));

// obviously it is not required to print the response. But you have

// to call con.getInputStream(). The connection is really established only

// when getInputStream() is called.

System.out.println("Output:");

for (String line = r.readLine(); line != null; line = r.readLine()) {

System.out.println(line);

}

我在这里使用了从Jakarta IO utils获取的copy()方法.这是供参考的代码:

protected static long copy(InputStream input, OutputStream output)

throws IOException {

byte[] buffer = new byte[12288]; // 12K

long count = 0L;

int n = 0;

while (-1 != (n = input.read(buffer))) {

output.write(buffer, 0, n);

count += n;

}

return count;

}

显然,服务器端必须准备好直接从POST主体读取图像内容.

我希望这有帮助.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值