Javascript 使用ng文件上载和angularjs进行内容处理
背景:Javascript 使用ng文件上载和angularjs进行内容处理,javascript,angularjs,fileapi,ng-file-upload,Javascript,Angularjs,Fileapi,Ng File Upload,背景: (function () { 'use strict'; angular .module('poc.fileUpload') .controller('SignupFileUpload', SignupFileUpload); SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerSer
(function () {
'use strict';
angular
.module('poc.fileUpload')
.controller('SignupFileUpload', SignupFileUpload);
SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll'];
function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll) {
$log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));
var params = $location.search();
var customerInfo = SignupService.getCustomerInfo();
var uploadData = {};
$log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));
if (typeof Object.keys(customerInfo)[0] === 'undefined') {
$log.debug('SIGNUP - Must provide customerInfo');
$location.path('/signup');
}
$scope.mobileUpload = function(form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Mobile Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('No Files are uploaded for mobile client');
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Mobile Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Mobile Upload progress ' + $scope.progress);
});
};
$scope.uploadFiles = function(idFile,addressFile,form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('Checking for files to upload');
if (idFile) {
$log.debug('idFile found, adding to uploadData');
uploadData.idDocument = idFile;
}
if (addressFile) {
$log.debug('addressFile found, adding to uploadData');
uploadData.addressDocument = addressFile;
}
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
// progress notify
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Upload progress ' + $scope.progress);
});
};
function handleError(error) {
usSpinnerService.stop('spinner');
scrollToServerMessage();
$scope.serverMessage = 'Signup failed with status ' + error.status;
}
function scrollToServerMessage() {
var old = $location.hash();
$location.hash('serverMessage');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
}
}
}());
我使用ng file upload在单独的ngf选择中提交两个文件,以及一个Javascript对象文本。我遇到的问题是,当发送请求时,所有部分的内容配置都设置为表单数据,但我希望这两个文件的内容配置是附件
问题:
(function () {
'use strict';
angular
.module('poc.fileUpload')
.controller('SignupFileUpload', SignupFileUpload);
SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll'];
function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll) {
$log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));
var params = $location.search();
var customerInfo = SignupService.getCustomerInfo();
var uploadData = {};
$log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));
if (typeof Object.keys(customerInfo)[0] === 'undefined') {
$log.debug('SIGNUP - Must provide customerInfo');
$location.path('/signup');
}
$scope.mobileUpload = function(form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Mobile Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('No Files are uploaded for mobile client');
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Mobile Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Mobile Upload progress ' + $scope.progress);
});
};
$scope.uploadFiles = function(idFile,addressFile,form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('Checking for files to upload');
if (idFile) {
$log.debug('idFile found, adding to uploadData');
uploadData.idDocument = idFile;
}
if (addressFile) {
$log.debug('addressFile found, adding to uploadData');
uploadData.addressDocument = addressFile;
}
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
// progress notify
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Upload progress ' + $scope.progress);
});
};
function handleError(error) {
usSpinnerService.stop('spinner');
scrollToServerMessage();
$scope.serverMessage = 'Signup failed with status ' + error.status;
}
function scrollToServerMessage() {
var old = $location.hash();
$location.hash('serverMessage');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
}
}
}());
我是否有办法覆盖表单部分的内容配置,使其成为文件的附件,而不是表单数据
代码
控制器:
(function () {
'use strict';
angular
.module('poc.fileUpload')
.controller('SignupFileUpload', SignupFileUpload);
SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll'];
function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll) {
$log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));
var params = $location.search();
var customerInfo = SignupService.getCustomerInfo();
var uploadData = {};
$log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));
if (typeof Object.keys(customerInfo)[0] === 'undefined') {
$log.debug('SIGNUP - Must provide customerInfo');
$location.path('/signup');
}
$scope.mobileUpload = function(form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Mobile Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('No Files are uploaded for mobile client');
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Mobile Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Mobile Upload progress ' + $scope.progress);
});
};
$scope.uploadFiles = function(idFile,addressFile,form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('Checking for files to upload');
if (idFile) {
$log.debug('idFile found, adding to uploadData');
uploadData.idDocument = idFile;
}
if (addressFile) {
$log.debug('addressFile found, adding to uploadData');
uploadData.addressDocument = addressFile;
}
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
Upload.upload({
url: URLS.BASE + URLS.FILE_UPLOAD,
data: uploadData
}).then(function (response) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Upload Status - ' + response.status);
$timeout(function () {
$scope.serverMessage = response.data;
});
if (response.status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}, function (response) {
// handle error
$log.debug('Signup failed with status ' + response.status);
handleError(response);
}, function (evt) {
// progress notify
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
$log.debug('Upload progress ' + $scope.progress);
});
};
function handleError(error) {
usSpinnerService.stop('spinner');
scrollToServerMessage();
$scope.serverMessage = 'Signup failed with status ' + error.status;
}
function scrollToServerMessage() {
var old = $location.hash();
$location.hash('serverMessage');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
}
}
}());
HTML
<form name="signupForm">
<div class="panel panel-default no-bottom-margin">
<div class="hidden-md hidden-lg">
<div class="panel-heading no-border">
<h2 class="panel-title" translate>ID Documents</h2>
<hr/>
</div>
<div class="panel-body">
<span><p>Document upload facility is not supported on mobile devices. Please send your ID documents to <a href="mailto:someone@somewhere.com" target="_top"><span>someone@somewhere.com</span></a> after you complete sign up.</p>
<p>You will need to scan and upload the following two documents:<br/>
- Proof of identity (passport or ID card)<br/>
- Proof of address (utility bill, bank statement or government issued letter within the last 3 months)</p></span>
</div>
<div class="panel-footer">
<div class="align-right">
<button type="button"
id="proceedBtn"
ng-click="mobileUpload(signupForm)" class="btn btn-sm xs-display-block"
translate>Complete Sign up
</button>
</div>
</div>
</div>
<div class="hidden-xs hidden-sm">
<div class="form-control-wrapper">
<div class="panel-heading no-border">
<h2 class="panel-title" translate>ID Documents</h2>
<hr/>
<p>Please upload a copy of your passport, drivers license, or any other government issued identification</p>
</div>
<div class="panel-body">
<div ng-class="{'has-error': signupForm.idfile.$invalid && signupForm.idfile.$dirty,
'has-success': signupForm.idfile.$valid}">
<div class="btn btn-sm btn-primary"
ngf-select=""
ngf-max-size="2MB"
ng-model="idFile"
accept="image/*,application/pdf"
ngf-pattern="'image/*,application/pdf'"
required="false"
id="idfile"
name="idfile"><span ng-if="signupForm.idfile.$valid">Change file</span><span ng-if="!signupForm.idfile.$valid">Add file</span>
</div>
<div class="popover-wrapper">
<a href=""
ng-show="!signupForm.idfile.$valid"
class="top-left"
role="button"
data-toggle="popover"
data-placement="top"
data-content-source="#popover-content"
data-trigger="click"
transcend-popover
content="{{'In order to set up your account, we need you to provide us with a copy of a valid national ID card or passport and a proof of address. These documents are kept safely for our records, and allow us to verify your identity. There is a limit of 2MB per file.' |translate}}">
<small><span class="icon-popover"></span> <span translate> Why is this needed?</span>
</small>
</a>
</div>
<div class="form-group has-error has-feedback" ng-show="signupForm.idfile.$error.maxSize">
<span class="input-status placement-left">File is too large, maximum size is 2MB</span>
</div>
<div ng-show="signupForm.idfile.$valid" class="form-control-wrapper">
<img ngf-thumbnail="idFile" class="thumb"/>
<div class="align-right">
<button ng-click="idFile = null" ng-show="idFile" class="btn btn-sm btn-warning">Remove</button>
</div>
</div>
</div>
</div>
<div class="panel-heading no-border">
<h2 class="panel-title" translate>Proof of address</h2>
<hr/>
<p>Please upload a copy of a utility bill or your driving licence</p>
</div>
<div class="panel-body">
<div ng-class="{'has-error': signupForm.addressfile.$invalid && signupForm.addressfile.$dirty,
'has-success': signupForm.addressfile.$valid}">
<div class="btn btn-sm btn-primary"
ngf-select=""
ngf-max-size="2MB"
ng-model="addressFile"
accept="image/*,application/pdf"
ngf-pattern="'image/*,application/pdf'"
required="false"
id="addressfile"
name="addressfile"><span ng-if="signupForm.addressfile.$valid">Change file</span><span ng-if="!signupForm.addressfile.$valid">Add file</span>
</div>
<div class="popover-wrapper">
<a href=""
ng-show="!signupForm.addressfile.$valid"
class="top-left"
role="button"
data-toggle="popover"
data-placement="top"
data-content-source="#popover-content"
data-trigger="click"
transcend-popover
content="{{'In order to set up your account, we need you to provide us with a copy of a valid national ID card or passport and a proof of address. These documents are kept safely for our records, and allow us to verify your identity. There is a limit of 2MB per file.' |translate}}">
<small><span class="icon-popover"></span> <span translate>Why is this needed?</span>
</small>
</a>
</div>
<div class="form-group has-error has-feedback" ng-show="signupForm.addressfile.$error.maxSize">
<span class="input-status placement-left">File is too large, max size is 2 MB</span>
</div>
<div ng-show="signupForm.addressfile.$valid" class="form-control-wrapper">
<img ngf-thumbnail="addressFile" class="thumb"/>
<div class="align-right">
<button ng-click="addressFile = null" ng-show="addressFile" class="btn btn-sm btn-warning">Remove</button>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="align-right">
<button type="button"
id="proceedBtn"
ng-click="uploadFiles(idFile,addressFile,signupForm)"
class="btn btn-primary"
translate>Complete Sign up
</button>
</div>
</div>
</div>
</div>
</div>
</form>
身份证件
移动设备上不支持文档上载功能。完成注册后,请将您的身份证明文件发送至
您需要扫描并上传以下两个文档:
-身份证明(护照或身份证)
-地址证明(过去3个月内的公用事业账单、银行对账单或政府出具的信函)
完全注册
身份证件
请上传您的护照、驾驶执照或任何其他政府颁发的身份证件副本
更改文件添加文件
文件太大,最大大小为2MB
去除
地址证明
请上传一份水电费账单或驾驶执照副本
更改文件添加文件
文件太大,最大大小为2 MB
去除
完全注册
当前请求:
因此,尽管没有一个库允许我这样做,但我仍然需要更改内容配置和其他事项,因此我在以下问题的帮助下成功地做到了这一点 我仍然在使用ng文件上传来实现UI中的各种有用功能,但在控制器中,我正在构建我自己的帖子
(function () {
'use strict';
angular
.module('poc.fileUploads')
.controller('SignupFileUpload', SignupFileUpload);
SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll','$http'];
function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll,$http) {
$log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));
var params = $location.search();
var customerInfo = SignupService.getCustomerInfo();
var uploadData = {};
$log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));
if (typeof Object.keys(customerInfo)[0] === 'undefined') {
$log.debug('SIGNUP - Must provide customerInfo');
$location.path('/signup');
}
$scope.uploadFiles = function(idFile,addressFile,form) {
usSpinnerService.spin('spinner');
$log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
$log.debug('Adding customerInfoPart to uploadData');
uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
$log.debug('Checking for files to upload');
if (idFile) {
$log.debug('idFile found, adding to uploadData');
uploadData.idDocument = idFile;
}
if (addressFile) {
$log.debug('addressFile found, adding to uploadData');
uploadData.addressDocument = addressFile;
}
$log.debug('Upload data - ' + JSON.stringify(uploadData));
$log.debug('Uploading data');
var epochTicks = 621355968000000000;
var ticksPerMillisecond = 10000;
var yourTicks = epochTicks + ((new Date()).getTime() * ticksPerMillisecond);
var boundary='---------------------------'+yourTicks;
var header='--'+boundary+'\r\n';
var footer='\r\n--'+boundary+'--\r\n';
var contenttype='multipart/form-data; boundary='+boundary;
var jsonContents=header+'Content-Disposition: form-data; name="customerInfoPart"\r\n';
jsonContents+='Content-Type: application/json\r\n';
jsonContents+='Content-Length: '+JSON.stringify(customerInfo).length+'\r\n\r\n';
jsonContents+=JSON.stringify(customerInfo)+'\r\n';
var idFileContents=header+'Content-Disposition: form-data; name="idDocument"; filename="'+$scope.idFile.name+'"\r\n';
idFileContents+='Content-Transfer-Encoding: binary\r\n';
idFileContents+='Content-Type: '+ $scope.idFile.type+'\r\n';
idFileContents+='Content-Length: '+ $scope.idFile.size +'\r\n\r\n';
var idFileReader = new FileReader();
// idFileReader.readAsArrayBuffer($scope.idFile);
var addressFileContents=header+'Content-Disposition: form-data; name="addressDocument"; filename="'+$scope.addressFile.name+'"\r\n';
addressFileContents+='Content-Transfer-Encoding: binary\r\n';
addressFileContents+='Content-Type: '+$scope.addressFile.type+'\r\n';
addressFileContents+='Content-Length: '+$scope.addressFile.size+'\r\n\r\n';
var addressFileReader = new FileReader();
// addressFileReader.readAsArrayBuffer($scope.addressFile);
var blob=new Blob([jsonContents,idFileReader.readAsArrayBuffer($scope.idFile),idFileReader,addressFileReader.readAsArrayBuffer($scope.addressFile),addressFileReader,footer]);
$log.debug(blob.toString());
$http.post(
URLS.BASE + URLS.FILE_UPLOAD,
blob,
{'headers':{'Content-Type':contenttype}}
).success(function (data, status, headers, config) {
// file is uploaded successfully
usSpinnerService.stop('spinner');
$log.debug('Upload Status - ' + status);
$timeout(function () {
$scope.serverMessage = data;
});
if (status===204) {
$location.path('/signup-confirmation');
SignupService.setCustomerSignupStatus(true);
}
}).error(function (data, status, headers, config) {
// handle error
$log.debug('Signup failed with status ' + status);
handleError(status);
});
};
function handleError(error) {
usSpinnerService.stop('spinner');
scrollToServerMessage();
$scope.serverMessage = 'Signup failed with status ' + error.status;
}
function scrollToServerMessage() {
var old = $location.hash();
$location.hash('serverMessage');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
}
}
}());
查看ng file upload中的FileAPI.js,我可以在第2621行看到有一个函数toMultiPartData:Line2626…'--'+-边界+('\r\n内容处理:表单数据;name=“+file.name+”+(file.file?;filename=“+encodeURIComponent(file.file)+'”:'')+(file.file?'\r\n内容类型:'+(file.Type | |“应用程序/八位字节流”):'')…我认为可能正是在这里,表单中的所有项目都设置了表单数据。我与ng文件上载中使用的FileAPI的作者进行了交谈,根据规范,表单数据是预期的内容配置。我对这一变化感到好奇,因为apache camel和apache cxf中的服务器端行为。我想我会i’我必须在那里寻找解决方案。我进一步查看了ietf.org/rfc/rfc1867.txt规范,在allI未能找到任何快速解决方法后,似乎content disposition=附件是一个有效的设置。与此同时,我正在考虑对Upload.Upload调用上的数据应用transformRequest并更改co以这种方式进行内容处理。除非您在IE8-9上测试FileAPI,否则这与FileAPI没有任何关系。文件将作为多部分/表单数据请求发送,因此每个部分的内容处理都是表单数据。如果您想直接发送文件二进制文件,可以使用
Upload.http()