【问题标题】:How to bind javascript array with @RequestParam using FormData?如何使用 FormData 将 javascript 数组与 @RequestParam 绑定?
【发布时间】:2017-12-20 08:00:14
【问题描述】:

问题是将javascript arraylist 与RequestParam 注释绑定。 如果没有 nokDataList,我有这样的表单数据可以正常工作。 nokInfoDatas 是一个 javascript 数组,在控制台中它看起来:

var requestData = JSON.stringify(nokInfoDatas);
    console.log("nokInfoDatas");
    console.log(nokInfoDatas);
    console.log("requestData");
    console.log(requestData);
var fd = new FormData();
        fd.append('photo', file);
        fd.append('testId', testId);
        fd.append('nokDataList', nokInfoDatas);
var ajaxData = {
            type: "POST",
            data: fd,
            processData : false,
            contentType : false,
            url: sendUrl,
            headers: headersData,
    };

后端:

public @ResponseBody String answer(HttpServletRequest request, 
            @RequestParam(value = "photo") MultipartFile photo,
            @RequestParam(value = "testId") String testId,
        @RequestParam(value = "nokDataList") List<NokDataDTO> nokInfoDtos
            )

【问题讨论】:

  • 可以发实体类吗? (NokDataDTO)
  • @harshil 它是一个基本的 java 类,具有:private Long id;私有字符串 nokInfo;私有字符串 nokData;
  • 有二传手吗?
  • @harshil 是的,两者都有 setter 和 getter

标签: javascript java ajax spring form-data


【解决方案1】:

你可以尝试如下:

使用您的 JSON 数据 (requestData) 创建一个Blob

var requestData = JSON.stringify(nokInfoDatas);
var fd = new FormData();
fd.append('photo', file);
fd.append('testId', testId);
fd.append('nokDataList', new Blob([requestData], {
  type: "application/json"
}));

将@RequestParam 更改为@RequestPart 以解析多部分的JSON。

public @ResponseBody String answer(HttpServletRequest request, 
       @RequestParam(value = "photo") MultipartFile photo,
       @RequestParam(value = "testId") String testId,
       @RequestPart(value = "nokDataList") List<NokDataDTO> nokInfoDtos
      )

【讨论】:

  • 对我不起作用,同样的绑定问题。顺便说一句,我没有使用像 json 这样的任何类型,因为当我用来传递文件时,它会爆炸。也许这就是为什么你的方法不起作用?
  • @DogaOzdemir 我尝试了代码并正常工作。也许您还需要 Spring 多部分配置。你可以查看我的配置here。我正在使用 Spring 4.3.3.RELEASE。
  • 删除文件追加后,绑定工作正常!但是有一个奇怪的事情是 List nokInfoDtos inside LinkedHashMap values
  • @DogaOzdemir 尝试删除 headers:headersData 您的 ajax 方法。我试过没有它。
  • 解决了这个问题:List nList= mapper.convertValue(nokInfoDtos, new TypeReference>() { });无论如何感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2016-06-30
  • 2017-12-16
  • 2012-12-25
  • 2018-04-07
相关资源
最近更新 更多