将图像上载到宁静的Web服务会产生不可见的图像

时间:2017-08-27 08:32:27

标签: java upload jersey inputstream multipartform-data

我使用以下解决方案尝试在用java编写的restful webservice中接收图像:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String getFile(@FormDataParam("pic") InputStream file,
        @QueryParam("uid") String uid) {

    try {
        storeFile(file, uid);
    } catch (IOException ex) {
        Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
        return "failed";
    }
    return "success";
}

private void storeFile(InputStream input, String uid) throws IOException {
    String absPath = PATH_TO_FILES + uid + ".jpg";
    try {
        OutputStream out = new FileOutputStream(new File(absPath));
        int read = 0;
        byte[] bytes = new byte[1024];

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

        e.printStackTrace();
    }
}

这是客户端代码(javascript):

$scope.fileSelect = function (files) {

var file = files[0];
  console.log("File loaded");
  console.log(files);
  console.log('uid = ' + $scope.uid + ' user = ' + $scope.user);
  var formData = new FormData();
  formData.append('pic', file);
  var requestBody = {"token": $scope.token};

    var req = {
        method: 'POST',
        url: 'http://192.168.0.9/resources/UploadPicture?uid=' + $scope.uid,
        headers: {
            'Content-Type': undefined
        },
        data: formData
    };
    console.log(FormData);
    $http(req).then(function(response){
        console.log(response);
    }, function(error){
        console.log(error);
    });


};

此代码生成一个无法查看的文件。我期待的文件是图像。 所以我有两个问题:

  1. 每当调用webservice并返回响应时,似乎图像没有完全刷新到硬盘。过了一会儿我可以编辑它。当图像实际刷新到磁盘时,有没有办法回复客户端?

  2. 如何将输入流写入磁盘时生成可视图像?

  3. - 编辑 -

    在摆弄文件之后,我意识到如果我在记事本++中编辑图像并取下表格边界的开始和结束标签,图像可以再次查看:

    Produced File

    表单边界是否有办法停止干扰图像数据?

1 个答案:

答案 0 :(得分:0)

我找到了一个使用apache commons fileupload的解决方案:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String getFile(@Context HttpServletRequest request, @QueryParam("uid") String uid) {


    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                System.out.println("Form field " + name + " with value "
                        + Streams.asString(stream) + " detected.");
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                // Process the input stream
              storeFile(stream, uid);
            }
        }

        return "success";

    } catch (FileUploadException ex) {
        Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadImage.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "failed.";
}