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 两次读取。从循环的主体中删除read语句,你会没事的。

您还说过您的问题中提供的代码适用于文本文件。我认为这也行不通。从您尝试上传的文件中读取两次意味着您只上传了一半的内容。半个文本文件还是个文本文件,但半个PDF只是垃圾,不能打开后者。您应该仔细检查您上传和保存的文本文件的内容是否与原始文件相同。

于 2012-01-09T11:39:21.860 回答