使用HTML5 File API将文件上载到RESTful Webservice

时间:2015-02-03 17:43:48

标签: java javascript rest file-upload jax-rs

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

JavaScript的:

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仍然很简陋,所以请不要怀疑我是否使用绝对目标路径。

谢谢, 格里

1 个答案:

答案 0 :(得分:0)

我从泽西岛改为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/