我正在尝试使用AngularJS和Spring MVC上传文件。
在application-context.xml中,我有一个multipartResolver bean。
<mvc:annotation-driven />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152" />
</bean>
我的表格长这样:
<form method="post" id="fromFileUpload" enctype="multipart/form-data"
ng-submit="continueFileUpload()">
<div class="form-group">
<label class="control-label col-sm-4 col-xs-12" for="quoteIdentifier">Quote Identifier : </label>
<div class="col-xs-4 input-max">
<select type="text" class="form-control " name="quoteIdentifier" id="quoteIdentifier" ng-model="quoteIdentifier" ng-options="">
<option style="display: none" value="">Choose</option>
</select>
</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=".csv,.xsl,.xml,.mpp,application/vnd.ms-excel">
</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> Continue
</button>
</div>
</div>
</form>
$scope.continueFileUpload=function (){
var uploadUrl=serverUrl+"continueFileUpload";
var formData=new FormData();
formData.append("file",file.files[0]);
$http({
method: 'POST',
url: uploadUrl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("success");
})
};
Spring 控制器:
@Controller
public class FileUploadController {
@RequestMapping(value = "/continueFileUpload", method = RequestMethod.POST)
@ResponseBody
public String continueFileUpload(HttpServletRequest request,
HttpServletResponse response){
MultipartHttpServletRequest mRequest;
try {
mRequest = (MultipartHttpServletRequest) request;
mRequest.getParameterMap();
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext()) {
MultipartFile mFile = mRequest.getFile(itr.next());
String fileName = mFile.getOriginalFilename();
System.out.println(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
当我在头部添加multipart/form-data时,我会收到“**请求被拒绝,因为找不到多部分边界**”的异常。
如果我没有添加,则会收到“org.apache.catalina.connector.RequestFacade无法转换为org.springframework.web.multipart.MultipartHttpServletRequest”的异常。