StackOverflow上已经有一些类似的问题。我经历了其中一些,但它们对我不起作用。因此,请不要将此问题标记为
duplicate
。
我想使用AngularJS将一个文件上载到用Kotlin编写的Spring控制器。为了做到这一点,我编写了下面的代码,但它不起作用。我得到一个
404
请求响应错误,消息为
Required request part 'file' is not present
输入
<form class="col-xs-12 col-sm-4 form-inline " ng-submit="$ctrl.saveFiles()">
<div class="form-group">
<label for="file-upload" class="custom-file-upload">
Choose File
</label>
<input id="file-upload" type="file" file-model="$ctrl.file" name="file"/>
</div>
<div class="form-group">
<button class="btn btn-primary pull-right" type="submit">Submit</button>
</div>
</form>
文件模型指令
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
我已从中复制了此指令
question
$ctrl。saveFiles()函数
$ctrl.saveFiles = function () {
// var file = document.getElementById("file-upload").files[0]
var formData = new FormData();
formData.append("file", $ctrl.file);
console.log(formData.has("file")); // true
var url = '/upload',
config = {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
};
return $http.post(url, formData, config)
};
弹簧@豆角
@Bean
open fun multipartResolver(): MultipartResolver {
val multipartResolver = CommonsMultipartResolver()
multipartResolver.setMaxUploadSize(500000000)
return multipartResolver
}
弹簧@后映射方法
@PostMapping(value = "/upload")
@Throws(Exception::class)
fun uploadFile(@RequestParam("file") file: MultipartFile): String {
return "Upload file"
}
请求标头
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4829202
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJ8BRhjvMRLt9UdRS
如你所见,我使用
Kotlin
,回答完全可以
Java
。