我在项目中使用angularjs。
i带有Extension .xlsx的老挝文件,我需要将其发布到Web服务和两个整数编号,即月和年。
这是html:
<div class="col-xs-5">
<label class="btn btn-success btn-sm">
Load File <input type="file" id="inptFile" onchange="$('#upload-file-info').html(this.files[0].name)" hidden>
</label>
<span class='label label-default' id="upload-file-info">. . .</span>
</div>
这是加载文件后发射的JavaScript代码:
$scope.loadFile = function () {
if (hasExtension('inptFile', ['.xlsx']))
{
var file = $('#inptFile')[0].files[0]; //get the file
//here post file to service.
}
else {}
}
function hasExtension(inputID, exts) {
var fileName = document.getElementById(inputID).value;
return (new RegExp('(' + exts.join('|').replace(/./g, '\.') + ')$')).test(fileName);
}
这是Web服务:
[WebMethod]
public List<DepartmentReport> SaveXml(int year, int month, file)
{
//some logic
}
在我获取文件(此行之后)后,var file = $('#inptfile')[0] .files [0]我需要将文件,每年和月发布到Web服务。
我如何使用AngularJS $ HTTP发布两个整数并将其归档到上面的Web服务?
在您的后端,您可以像这样处理文件上传:
@PostMapping("/{year}/{month}")
public ResponseEntity<List<DepartmentReport>> saveXml(@PathVariable("year") Integer year,
@PathVariable("month") Integer month
@RequestParam("file") MultipartFile file) {
// TODO
}
说明
您可以使用PathVariable
注释处理文件和参数。这样,它将为您的uplaod定义一个休息URL: <endpoint>/2017/12
。
您也可以使用RequestParam
注释而不是PathVariable
。它会将您的URL更改为此类<endpoint>?year=2017&month=12
。
imo,第一个选项看起来更好。
使用AngularJS,您可以像这样处理文件上传:
$http({
method: 'POST',
url: '<endpoint>/' + year + '/' + month,
headers: {
'Content-Type': 'multipart/form-data'
},
data: $scope.file
})
.success(function (data) {
})
.error(function (data, status) {
});
请注意,我没有测试任何一个,但我希望这对您有帮助。
文档:
- Sprint引导文档上传文件
- 堆栈溢出答案:AngularJS $ HTTP POST FILE和FORM DATA