4

DropboxのAPIを使用するJerseyサービスを開発しています。

汎用ファイルをサービスに投稿する必要があります(サービスは、Dropbox APIで実行できるのと同様に、あらゆる種類のファイルを管理できます)。

クライアント側

そこで、次のような単純なクライアントを実装しました。

  • ファイルを開き、
  • URLへの接続を作成し、
  • 正しいHTTPメソッドを設定します。
  • を作成し、FileInputStreamバイトバッファを使用して接続の出力ストリームにファイルを書き込みます。

これはクライアントのテストコードです。

public class Client {

  public static void main(String args[]) throws IOException, InterruptedException {
    String target = "http://localhost:8080/DCService/REST/professor/upload";
    URL putUrl = new URL(target);
    HttpURLConnection connection = (HttpURLConnection) putUrl.openConnection();

    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("content-Type", "application/pdf");

    OutputStream os = connection.getOutputStream();

    InputStream is = new FileInputStream("welcome.pdf");
    byte buf[] = new byte[1024];
    int len;
    int lung = 0;
    while ((len = is.read(buf)) > 0) {
      System.out.print(len);
      lung += len;
      is.read(buf);
      os.write(buf, 0, len);
    }
  }
}

サーバ側

私は次のような方法を持っています:

  • InputStream引数としてを取得し、
  • 元のファイルと同じ名前とタイプのファイルを作成します。

次のコードは、特定のPDFファイルを受信するためのテストメソッドを実装しています。

@PUT
@Path("/upload")
@Consumes("application/pdf")
public Response uploadMaterial(InputStream is) throws IOException {
  String name = "info";
  String type = "exerc";
  String description = "not defined";
  Integer c = 10;
  Integer p = 131;
  File f = null;
  try {
    f = new File("welcome.pdf");

    OutputStream out = new FileOutputStream(f);
    byte buf[] = new byte[1024];
    int len;
    while ((len = is.read(buf)) > 0)
      out.write(buf, 0, len);
    out.close();
    is.close();
    System.out.println("\nFile is created........");
  } catch (IOException e) {
    throw new WebApplicationException(Response.Status.BAD_REQUEST);
  }

  //I need to pass a java.io.file object to this method
  professorManager.uploadMaterial(name, type, description, c,p, f);

  return Response.ok("<result>File " + name + " was uploaded</result>").build();
}

この実装は、テキストファイルでのみ機能します。単純なPDFを送信しようとすると、受信したファイルが読み取れなくなります(ディスクに保存した後)。

どうすれば要件を満たすことができますか?誰かが私に解決策を提案できますか?

4

1 に答える 1

7

あなたはクライアントコードに欠陥があります。

while ((len = is.read(buf)) > 0) {
  ...
  is.read(buf);
  ...
}

あなたはすべての反復でInputStream 2回から読んでいます。readループの本体からステートメントを削除すれば、問題はありません。

また、質問で提示されたコードはテキストファイルで機能するとも言っています。それもうまくいかないと思います。アップロードしようとしているファイルから2回読み取るということは、その内容の半分だけをアップロードしていることを意味します。テキストファイルの半分はまだテキストファイルですが、PDFの半分はごみであるため、後者を開くことはできません。アップロードおよび保存されたテキストファイルの内容が元のファイルと同じであるかどうかを再確認する必要があります。

于 2012-01-09T11:39:21.860 に答える