通过 URLConnection 写入图像

2024-02-28

我正在尝试通过 HttpURLConnection 写入图像。

我知道如何写文字,但我在尝试时遇到了真正的问题 写一个图像

我已经使用ImageIO成功写入本地硬盘:

但我试图通过 ImageIO 在 url 上写入 Image 并失败

URL url = new URL(uploadURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "multipart/form-data;
                                            boundary=" + boundary);
output = new DataOutputStream(connection.getOutputStream());
output.writeBytes("--" + boundary + "\r\n");
output.writeBytes("Content-Disposition: form-data; name=\"" + FIELD_NAME + "\";
                                            filename=\"" + fileName + "\"\r\n");
output.writeBytes("Content-Type: " + dataMimeType + "\r\n");
output.writeBytes("Content-Transfer-Encoding: binary\r\n\r\n");
ImageIO.write(image, imageType, output);

uploadURL 是服务器上的 ASP 页面的 url,该页面将使用“content-Disposition:part.txt”中给出的文件名上传图像。

现在,当我发送此信息时,ASP 页面会找到请求并找到文件名。但没有找到要上传的文件。

问题是当 ImageIO 在 URL 上写入时,ImageIO 正在写入的文件的名称是什么,

所以请帮助我 ImageIO 如何在 URLConnection 上写入图像以及我如何知道我必须在 asp 页面中使用的文件名来上传文件

感谢您花时间阅读这篇文章 迪利普·阿加瓦尔


首先我相信你应该打电话io.flush()进而io.close()写入图像后。

第二种内容类型对我来说似乎很奇怪。看来您正在尝试提交表单,而它实际上是图像。我不知道你的 asp 期望什么,但通常当我编写应该通过 HTTP 传输文件的代码时,我会发送适当的内容类型,例如image/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 正文读取图像内容。 我希望这有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 URLConnection 写入图像 的相关文章

随机推荐