我正在使用angularJs和spring 4.0,
我的控制器代码:
@RequestMapping(value = "/endpoint/add", method = RequestMethod.POST)
public @ResponseBody GenericFormResponse execute(
WebRequest wreq,
@RequestParam("epName") String epName,
@RequestParam("ipAddr") String ipAddr,
@RequestParam("useDefault") String useDefault,
@RequestParam("certFile") MultipartFile certFile) throws Exception {
.....................
}
我的js(angualrJs)代码:
var formData = new FormData();
formData.append("epName", $scope.epName);
formData.append("ipAddr", $scope.ipAddr);
formData.append("useDefault",$scope.defaultCert);
if(!$scope.defaultCert){
formData.append("certFile", upFile);
}
$http({
method: "POST",
url: "./service/endpoint/add",
data: formData,
transformRequest: angular.identity,
headers: {'Content-Type': undefined }
}).success(svcSuccessHandler)
.error(svcErrorHandler);
我的问题是
$scope.defaultCert=false
POST请求运行正常,$scope.defaultCert = true
我收到错误的请求(400)。我也在下面尝试过
if(!$scope.defaultCert){
formData.append("certFile", upFile);
}else{
formData.append("certFile", null);
}
我如何发送空的
MultipartFile
。谢谢。
最佳答案
我在控制器中创建了两个服务,并为两个创建了两个URL
@RequestMapping(value = "/endpoint/add-with-cert", method = RequestMethod.POST)
public @ResponseBody GenericFormResponse excecuteWithCert(
WebRequest wreq,
@RequestParam("epName") String epName,
@RequestParam("ipAddr") String ipAddr,
@RequestParam("useDefault") boolean useDefault,
@RequestParam("certFile") MultipartFile certFile) throws Exception {
LOGGER.debug("received request for endpoint creation with certificate");
GenericFormResponse response = new GenericFormResponse();
SessionManager sessionMgr = new SessionManager(wreq);
if(!sessionMgr.isLoggedIn()) {
response.setSuccess(false);
response.setGlobalErrorCode("not_logged_in");
return response;
}
...............
}
@RequestMapping(value = "/endpoint/add", method = RequestMethod.POST)
public @ResponseBody GenericFormResponse excecuteWithOutCert(
WebRequest wreq,
@RequestParam("epName") String epName,
@RequestParam("ipAddr") String ipAddr,
@RequestParam("useDefault") boolean useDefault) throws Exception {
LOGGER.debug("received request for endpoint creation without certificate");
...............
}
在js文件中:
var url = "./service/endpoint/add";
if(!$scope.defaultCert){
formData.append("certFile", upFile);
url = "./service/endpoint/add-with-cert";
}
$http({
method: "POST",
url: url,
data: formData,
transformRequest: angular.identity, headers: {'Content-Type': undefined }
}).success(svcSuccessHandler)
.error(svcErrorHandler);
我不知道这是正确的方法,还是可以满足我的要求。按我的预期工作。请提出最佳答案。
关于java - 如何为MultipartFile发送空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27188834/