使用 HTML5 文件 API 将文件上传到 RESTful Web 服务

Upload file to RESTful Webservice with HTML5 File API

我正在尝试将带有 HTML5 文件 API 的文件上传到 Java RESTful Web 服务。当我尝试上传 gif 图像时,服务正在接收 InputStream,我可以将该流写入服务器文件系统。不幸的是出了点问题,因为创建的图像(689 字节)比源文件(512 字节)大。这是我已经拥有的:

Java脚本:

var doc = document.documentElement;
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();

  // now do something with:
  var files = event.dataTransfer.files;
  var formData = new FormData();
  for (var i = 0; i < files.length; i++) {
    formData.append('file', files[i]);
  }

  // now post a new XHR request
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'rs/media/upload', true);
  xhr.onload = function () {
    if (xhr.status === 200) {
      console.log('all done: ' + xhr.status);
    } else {
      console.log('Something went terribly wrong...');
    }
  };

  xhr.send(formData);
  return false;
};

Java RESTful 服务:

  @POST
  @Path("upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream) throws IOException
  {
    if (uploadedInputStream == null) {
      return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }

    writeToFile(uploadedInputStream, MEDIA_BASE_PATH + "/test.gif");

    return Response.status(Response.Status.OK).build();
  }

  private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation)
  {

    try {
      OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
      int read = 0;
      byte[] bytes = new byte[1024];

      out = new FileOutputStream(new File(uploadedFileLocation));
      while ((read = uploadedInputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
      }
      out.flush();
      out.close();
    } catch (IOException e) {

      e.printStackTrace();
    }
  }

有人能告诉我这里有什么问题吗? WebService 仍然是初级的,所以请不要奇怪我使用的是绝对目标路径。

谢谢, 格里

我从 Jersey 更改为 RESTeasy,现在一切正常。这是我的新 REST 方法:

  @POST
  @Path("upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(@MultipartForm FileUploadForm form) throws IOException
  {
    if (form == null) {
      return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }

    Files.write(Paths.get(MEDIA_BASE_PATH + "/test.gif"), form.getData());

    return Response.status(Response.Status.OK).build();
  }

来源:http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/