我们正在使用Spring 4(基于注释的配置)和AngularJS来构建我们的应用程序。在其中一个用例中,我们需要上传文档。在提交表单时,我们需要发送表单数据(除文件上传文件外,还有作为表单一部分的字段)和文件内容作为POST请求的一部分。
@Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
HTML表单内容:
<form method="post" id="fromFileUpload"
enctype="multipart/form-data" ng-submit="create()">
<div class="form-group">
<label for="inputValue" class="col-md-offset-2 col-md-4 form-element">Input Value</label>
<div class="col-md-6 form-element">
<input class="form-control" ng-model="model.value"
name="val" required autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4 col-xs-12" for="file">Please
upload the file : <span class="required">*</span>
</label>
<div class="col-xs-4 input-max controls ">
<input class="inline-block" type="file" name="file"
ng-model="file" data-rule-required="true" id="file"
accept=".xls">
</div>
<span id="vaildFile" class="text-success icon-ok hide">Valid
File</span> <span id="invaildFile" class="text-error icon-remove hide">
Invalid File</span>
</div>
<div class="box-header">
<div class="actions">
<button type="submit" class="btn btn-primary">
<i class="icon-arrow-right"></i> Create
</button>
</div>
</div>
</form>
下面是angularJS代码:
$scope.create = function() {
var formData=new FormData();
formData.append("file",$scope.file);
formData.append("docData", angular.toJson($scope.model));
console.log(formData);
$http({
method: 'POST',
url: "http://localhost:8080/saprof/value",
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headers) {
return data;
}
})
.success(function(data, status) {
alert("Success");
})
.error(function(data, status) {
alert("Error");
});
};
以下是控制器代码(使用@RestController注释)
@RequestMapping(value="/saprof/value", method=RequestMethod.POST)
public void createValue(HttpServletRequest request, HttpServletResponse response, HttpSession session){
LOGGER.info("Request is of type MultiPartRequest "+(request instanceof MultipartHttpServletRequest)); // false
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
LOGGER.info("isMultiPart Request : "+isMultipart); // false
}
问题:
我将RequestFacade对象作为请求对象,而不是MultiPartServletRequest。因此,我无法从此请求中检索表单数据+文件内容。
当看到使用浏览器发送的请求时,以下是内容:
Request Payload
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="file"
[object Object]
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="docData"
{"value":"test"}
------WebKitFormBoundaryzfZtWVlK6xH8aSyf--
需要你的帮助来纠正我的错误。如果您需要任何进一步的细节,请告诉我。非常感谢您的帮助。
此致 Manjunath