3

HttpURLConnectionで画像を書き込もうとしています。URLConnectionを介した画像の書き込み

私はテキストを書く方法を知っているが、私は画像

を書くこと をしようと本当の問題が生じています、私はImageIOでを使用して、ローカルHDへの書き込みに成功している:

しかし、私はしてイメージを記述しようとしていますURL上のImageIOとは

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です失敗:一部

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

問題は、URLにImageIOにで書くとき何ImageIOには書き込みされているファイル、

の名前はそうImageIOには、URLConnectionの上の画像を書きますか私を助けてくださいますし、どのように私は知ることができるということです私はあなたがio.flush()を呼ぶべきであると信じているこのポスト ディリップAgarwalさん

答えて

4

最初に読むのに時間を割いて、ファイルに

感謝をアップロードするASPページで使用する必要があるファイルの名前と書き込み後、次にio.close()画像。

第2のコンテンツタイプは私にとっては奇妙なようです。あなたが実際にイメージである間にフォームを提出しようとしているようです。私はあなたのASPが何を期待しているのか分からないが、通常はHTTP経由でファイルを転送するコードを書くときに適切なコンテンツタイプを送信する。 image/jpeg。私はジャカルタIO utilsパッケージから取った私はここにメソッドのコピーを使用

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); 
    } 

():ここで

は、私は私の現在の仕事中に私が書いたと私は使用しています一つの小さなユーティリティから抽出されたサンプルコードスニペット用です。

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

実際に私はクライアントサイドのアプレットを使用しているので、クライアントのファイルシステムにアクセスすることはできません。また、ImageIOの助けを借りてチャートのイメージを作成する必要があります。それはファイルシステム上で書いている間に働く)。だからImageIOから直接URLConnectionに書き込む必要があります。その理由は、ImageIOがイメージコンテンツをURLConnection上のイメージファイルとして書き込む方法と、そのイメージファイルの名前を設定したり、そのイメージファイルの名前を知る方法を質問している理由です。 –

+0

'con.setDoOutput(true);' implies ' con.setRequestMethod( "POST"); 'また、 'OutputStream out = con.getOutputStream();'と 'con.getOutputStream();'をもう一度呼び出します。また、 'out.close();'は 'out.flush();'を呼び出します(そしてfinallyブロック内にあるはずです)。あなたの担当者には、より洗練されたコードを書くべきです –

+0

"接続は実際にはgetInputStream()が呼び出されたときにのみ確立されます。" - >そうではありません - ドキュメントへのリンクを提供できますか? –

0

OPは忘却の彼方に失ったが、ミスターカイトの利益のためと思われる:

// main method 
URL url = new URL(uploadURL); 
connection = (HttpURLConnection) url.openConnection(); 
connection.setDoOutput(true); // triggers "POST" 
// connection.setDoInput(true); // only if needed 
connection.setUseCaches(false); // dunno 
final String boundary = Long.toHexString(System.currentTimeMillis()); 
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" 
                   + boundary); 
output = new DataOutputStream(connection.getOutputStream()); 
try { 
    // image must be a File instance 
    flushMultiPartData(image, output, boundary); 
} catch (IOException e) { 
    System.out.println("IOException in flushMultiPartData : " + e); 
    return; 
} 
// ... 
private void flushMultiPartData(File file, OutputStream serverOutputStream, 
      String boundary) throws FileNotFoundException, IOException { 
    // SEE https://stackoverflow.com/a/2793153/281545 
    PrintWriter writer = null; 
    try { 
     // true = autoFlush, important! 
     writer = new PrintWriter(new OutputStreamWriter(serverOutputStream, 
       charsetForMultipartHeaders), true); 
     appendBinary(file, boundary, writer, serverOutputStream); 
     // End of multipart/form-data. 
     writer.append("--" + boundary + "--").append(CRLF); 
    } finally { 
     if (writer != null) writer.close(); 
    } 
} 

private void appendBinary(File file, String boundary, PrintWriter writer, 
     OutputStream output) throws FileNotFoundException, IOException { 
    // Send binary file. 
    writer.append("--" + boundary).append(CRLF); 
    writer.append(
     "Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" 
      + file.getName() + "\"").append(CRLF); 
    writer.append("Content-Type: " 
      + URLConnection.guessContentTypeFromName(file.getName())) 
      .append(CRLF); 
    writer.append("Content-Transfer-Encoding: binary").append(CRLF); 
    writer.append(CRLF).flush(); 
    InputStream input = null; 
    try { 
     input = new FileInputStream(file); 
     byte[] buffer = new byte[1024]; 
     for (int length = 0; (length = input.read(buffer)) > 0;) { 
      output.write(buffer, 0, length); 
     } 
     output.flush(); // Important! Output cannot be closed. Close of 
     // writer will close output as well. 
    } finally { 
     if (input != null) try { 
      input.close(); 
     } catch (IOException logOrIgnore) {} 
    } 
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of 
    // binary boundary. 
} 

あなたは、Gzip圧縮を追加することができます - をGzipの有無にかかわらず労働者階級のためのfile corrupted when I post it to the servlet using GZIPOutputStreamを参照してください。 ImageIOにはの場所はありません。 - ワイヤを通過したバイトを書き込み、ImageIOをサーバーの心臓のコンテンツに使用します。 @BalusCに基づいてanswer

関連する問題