繁体   English   中英

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

[英]Upload file to RESTful Webservice with HTML5 File API

我正在尝试使用HTML5 File 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仍然是基本的,因此请不要怀疑我使用的是绝对目标路径。

谢谢,格里

我从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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM