我想以角度上传文件。我试过以下:
<div >
<form enctype="multipart/form-data" method="post" novalidate name="form">
<input type="file" onchange="angular.element(this).scope().setFile(this)" required>
{{files.name}}
<div >
<button type="button" ng-class="{'tbt-btn':true, 'primary-btn':true}" ng-click="uploadFile(form,files)">Save</button>
</div>
</form>
</div>
JS ---
$scope.uploadFile = function (form,files) {
if (form.$invalid) return;
var path = files;
var uploadProgress = function (e) {
if (e.lengthComputable) {
var percent = Math.round(e.loaded * 100 / e.total);
console.log('upload progress: ' + percent + '%');
}
},
uploadComplete = function (e) {
if (e.target.status !== 200) {
uploadError(e);
return;
}
var locations = JSON.parse(e.target.responseText);
//function I want to call
},
uploadError = function (e) {
},
uploadAbort = function (e) {
};
var fd = new FormData();
var files = files;
for (var i = 0; i < files.length; i++) {
fd.append("file", files[i]);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadError, false);
xhr.addEventListener("abort", uploadAbort, false);
xhr.open("POST", "/fileupload");
xhr.send(fd);
}
但它不起作用。我收到错误 - “缺少初始多部分边界” 另外,我不确定我需要在xhr.open();中传递什么参数。 你能帮帮我吗?
由于
答案 0 :(得分:0)
您可以使用此简单控件上传文件:
HTML:
<input type="file" data-ng-model="fileName" class="form-control" onchange="angular.element(this).scope().uploadFile(this.files)"
name="file">
控制器:
$scope.uploadFile = function (files) {
var fd = new FormData();
fd.append("file", files[0]);
"your api with (fd)".then(function (response) {
if (files && files[0]) {
var reader = new FileReader();
reader.onload = function (e:any) {
$('#blah').attr('src', e.target.result).width(190).height(200);
};
reader.readAsDataURL(files[0]);
}
$scope.imageName = response;
})
};