java - Angularjs 将文件多部分 FormData 中的空值传递给 Spring MVC

标签 java angularjs file spring-mvc multipartform-data

我正在尝试将带有多部分数据(图像)的表单数据发送到 Spring MVC Controller 。从我的表格来看。图像字段不是强制性的。因此,当我在没有输入图像字段的情况下调用 spring Controller 时,我在浏览器控制台中收到以下错误。

Failed to load resource: the server responded with a status of 400 (Bad Request)

HTML 代码:

<input file="file" type="file" id ="file2"/>

AngularjS 代码:

$scope.saveData = function (formObj) {
    $http({
        url: CONTEXT_PATH+'saveFile',
        method: "POST",
        headers: { 'Content-Type': undefined },
        transformRequest: function (data) {
            alert(data.files);
            var formData = new FormData();
            formData.append("model", angular.toJson(data.model));
            formData.append("file", data.files);
            return formData;
        },
        data: { model: formObj, files: $scope.file }
    }).then(function (response) {
        //alert(response);
    });
};


app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
});

Spring Controller 代码:

@RequestMapping(value = "/saveFile")
public @ResponseBody String storeAd(@RequestParam ("model") String adString, @RequestParam ("file") MultipartFile file) throws IOException {
    System.out.println("adString > "+adString);
    return "OK";
}

最佳答案

当图像未上传时,请求是错误的,因为除非另有定义,否则 Spring MVC 假定所有必需的参数。 对于您的情况,您应该添加 required = false

@RequestParam(value = "file", required = false)

关于java - Angularjs 将文件多部分 FormData 中的空值传递给 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57606993/

相关文章:

java - 如果 firebase 中存在相同的值,如何创建条件

java - 创建 JWT token 时出现问题

c++ - 如何在 C++ 中将文本文件传输到二维数组?

Java - 如何从绝对路径中获取文件名并删除其文件扩展名?

c - 使用文件存储日历

java - 在 JUnit 中使用相同测试数据重复多个测试的简洁方法

java | Selenium |使用 Stream 从 Web 元素列表中返回单个 Web 元素

javascript - Angularjs ui utils 突出显示过滤器破坏了搜索应用程序

angularjs - IE 11 - 图像在破坏 View 后保留在浏览器内存中

unit-testing - 测试 Angular 服务给出错误 : No module: ngResource