无法在Rest API中读取InputStream数据

时间:2018-07-08 09:34:50

标签: java rest inputstream image-uploading multipartform-data

我正在将文件/ img(表单数据)从我的角度应用程序传递到我的rest api,作为post方法主体。 但是我无法读取inputStream内容。

我的Rest api方法:-

    @RequestMapping(path = "/upload", method = RequestMethod.POST)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void process(@FormDataParam("file") InputStream dataStream) throws IOException {

    this.writeToFile(dataStream, "src/main/resources/targetFile.jpg");
}

    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {

    try {
        byte[] image = IOUtils.toByteArray(uploadedInputStream);

        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));

        IOUtils.write(image, out);

        out.flush();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

图像数组始终为空,因此在目标目录中创建了空文件。 实施有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您可以像这样编写休息服务代码。

控制器方法

@RequestMapping(value="/upload", method=RequestMethod.POST)
public void handleFileUpload(@RequestParam("file") MultipartFile file){
    writeToFile(file, "src/main/resources/targetFile.jpg");
}

writeToFile方法

private void writeToFile(MultipartFile file, String uploadedFileLocation) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(uploadedFileLocation)));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    } else {
        System.out.println("Empty file");
    }
}