繁体   English   中英

用于文件上传和JSON数据的Rest Service Java

[英]Rest service Java for file upload and JSON data

我可以使用可用于文件上传的Rest服务,即多部分表单数据和JSON参数吗? 以下是该服务的示例。

    @POST
    @Path("/upload")
    @Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,@FormDataParam("file") FormDataContentDisposition fileDetail, City city){

问题是在测试时,我试图同时将文件作为附件和城市对象作为JSON传递,这给我带来了错误,因为Content-Type可能是application/jsonmultipart/form-data

让我知道是否有任何方法可以解决这个问题

您可以使用任何客户端语言来提交包含MultipartFile和Json数据的表单。 我在这里用Spring MVC编写Java代码。 它将发送String Json和MultiPartFile。 然后我要将String JSON转换为Map,并在所需位置保存文件。

@RequestMapping(value="/hotel-save-update", method=RequestMethod.POST )
public @ResponseBody Map<String,Object> postFile(@RequestParam(value="file", required = false) MultipartFile file,
                                     @RequestParam(value = "data") String object ){

    Map<String,Object> map = new HashMap<String, Object>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        map = mapper.readValue(object, new TypeReference<Map<String, String>>(){});
    }catch (Exception ex){
        ex.printStackTrace();
    }

    String fileName = null;

    if (file != null && !file.isEmpty()) {
        try {

            fileName = file.getOriginalFilename();
            FileCopyUtils.copy(file.getBytes(), new FileOutputStream(servletContext.getRealPath("/resources/assets/images/hotelImages") + "/" + fileName));

        } catch (Exception e) {
            header.put(Utils.MESSAGE, "Image not uploaded! Exception occured!");
            return result;
        }
    }

}

您是否不能关闭@Consumes并检查方法本身中的Content-Type标头,以决定在代码中做什么? 您的问题似乎是该批注功能的限制(是Spring MVC吗?)

我已经解决了问题,方法是从客户端将JSON作为字符串传递,然后将String转换为JSON对象。

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
                                @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("city") String city){

暂无
暂无

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

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