JSON对象和Multipart文件上载不起作用

时间:2015-09-16 12:28:37

标签: json angularjs spring spring-mvc

我们有Angular Controller如下

$scope.uploadData = function (files, data) {
                var fd = new FormData();
                fd.append("CustomerName", "Mahesh"); //As of now mocking the entities for creating form data 
                fd.append("CustomerID ", "44444");
                fd.append("ProductList",  JSON.stringify([{ProductID: '0001', ProductName: 'Samsung'},{ProductID: '0002', ProductName: 'Voldats'}]));
                fd.append("file", files[0]);
                fd.append("file", files[1]);
                inventoryService.Postfile(fd);                    
            }

Restangular帖子如下

Postfile : function (formData) {
                return restangular.all("postfile").withHttpConfig({transformRequest: angular.identity}).customPOST(formData, '', undefined, {'Content-Type': undefined});
                 },

Java VOs如下

public class ProductList implements Serializable{
private String ProductID;
private String ProductName;

public String getProductID() {
    return ProductID;
}

public void setProductID(String productID) {
    ProductID = productID;
}

public String getProductName() {
    return ProductName;
}

public void setProductName(String productName) {
    ProductName = productName;
}

}

public class CustomerList implements Serializable{
String CustomerName;
String CustomerID;
List<ProductList> ProductList;

public String getCustomerName() {
    return CustomerName;
}

public void setCustomerName(String customerName) {
    CustomerName = customerName;
}

public String getCustomerID() {
    return CustomerID;
}

public void setCustomerID(String customerID) {
    CustomerID = customerID;
}

public List<ProductList> getProductList() {
    return ProductList;
}

public void setProductList(List<ProductList> productList) {
    ProductList = productList;
}
}

Spring控制器如下

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/api/postfile", method = RequestMethod.POST)
public @ResponseBody
IhmsVO postfile(@RequestParam("file") List<MultipartFile> files,
        @ModelAttribute(value = "data") CustomerList vo, BindingResult bindingResult, Model model) {

    System.out.println("Post file");
    System.out.println(vo.getProductList());
    System.out.println("Files :: " + files + "  " + files.size());
    return null;
}

我们已经上传了两个文件,JSON对象,CustomerName和CustomerID已正确映射到相应的VO,但ProductList未与VO映射。我们在ProductList中获取null,为参考附加了调试模式屏幕截图。可以帮忙解决这个问题吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

您必须使用具有正确内容类型的Blob来传递JSON数据并将其添加到表单(https://developer.mozilla.org/en/docs/Web/API/Blob),例如:

fd.append("ProductList",  new Blob([ JSON.stringify([{ProductID: '0001', ProductName: 'Samsung'},{ProductID: '0002', ProductName: 'Voldats'}]) ], { type: "application/json" }));

编辑:将代码更新为绝对清晰,避免任何拼写错误,区分大小写问题,错误放置括号等。