【问题标题】:Uploading an Image to a restful webservice produces an unviewable image将图像上传到 RESTful Web 服务会产生无法查看的图像
【发布时间】:2018-02-04 18:50:54
【问题描述】:

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

@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. 每当调用 web 服务并返回响应时,似乎图像并未完全刷新到硬盘。一段时间后我可以编辑它。有没有办法在图像实际刷到磁盘时回复客户端?

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

--编辑--

在对文件进行了一些摆弄之后,我意识到如果我在 notepad++ 中编辑图像并去掉表单边界的开始和结束标记,图像就可以再次查看:

Produced File

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

【问题讨论】:

  • 你是如何上传文件的?你能展示你的客户程序吗?
  • 我添加了客户端代码

标签: java upload jersey inputstream multipartform-data


【解决方案1】:

我找到了使用 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.";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多