3

HttpURLConnection を介して画像を書き込もうとしています。

テキストの書き方は知っていますが、画像を書こうとすると本当に問題が発生します

ImageIO を使用してローカル HD への書き込みに成功しました。

しかし、URLにImageIOで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 は、"content-Disposition: パート.

これを送信すると、aspページがリクエストを見つけてファイルの名前を見つけます。しかし、アップロードするファイルが見つかりません。

問題は、URL に ImageIO で書き込む場合、ImageIO が書き込んでいるファイルの名前は何になるかということです。

ImageIOがURLConnectionに画像を書き込む方法と、ファイルをアップロードするためにaspページで使用する必要があるファイルの名前を知る方法を教えてください

この投稿をお読みいただきありがとうございます Dilip Agarwal

4

2 に答える 2

5

io.flush()最初に電話してから、io.close()画像を書いた後に呼び出す必要があると思います。

2 番目のコンテンツ タイプは奇妙に思えます。実際には画像であるのに、フォームを送信しようとしているようです。あなたのASPが何を期待しているのかわかりませんが、通常、HTTP経由でファイルを転送するコードを書くときは、適切なコンテンツタイプを送信しますimage/jpeg.

これは、私が作成し、現在の作業中に使用している 1 つの小さなユーティリティから抽出したコード スニペットの例です。

    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 本文から直接画像コンテンツを読み取る準備ができている必要があります。これが役立つことを願っています。

于 2011-02-03T07:48:47.773 に答える