使用 xhr 表单数据上传进度 javascript
form data upload progress using xhr javascript
我编写了一个服务,允许我将给定的文件连同 json 对象上传到给定的 url。我的代码是:
(function() {
angular.module('petrofacApp')
.service("fileUpload", fileUpload);
function fileUpload() {
function uploadFileToUrl(file, uploadUrl, jsonRequest, callback){
var fd = new FormData();
fd.append('JsonRequestData', JSON.stringify(jsonRequest));
fd.append('file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.response);
}
};
xhr.open('POST', uploadUrl, true);
xhr.send(fd);
}
return {
uploadFileToUrl: uploadFileToUrl
}
}
}());
我的问题是 - 如果我提到 onprogress 事件
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
文件上传没有任何问题,但 onprogress 事件仅在上传完成时触发一次。
我发现,为了避免这个问题,我必须使用 upload.onprogress。所以我将代码更改为
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
当我执行这个时,我得到错误-
XMLHttpRequest 无法加载 http://192.168.xxx.xxx:6152/api/UploadFile。预检响应具有无效的 HTTP 状态代码 405。
请帮我解决这个问题。
问题与 CORS 有关。我通过从 Nuget 安装 "CORS" 然后将以下代码添加到 WebApi.config 文件
从服务器端修复了它
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
这解决了我的问题。
我编写了一个服务,允许我将给定的文件连同 json 对象上传到给定的 url。我的代码是:
(function() {
angular.module('petrofacApp')
.service("fileUpload", fileUpload);
function fileUpload() {
function uploadFileToUrl(file, uploadUrl, jsonRequest, callback){
var fd = new FormData();
fd.append('JsonRequestData', JSON.stringify(jsonRequest));
fd.append('file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.response);
}
};
xhr.open('POST', uploadUrl, true);
xhr.send(fd);
}
return {
uploadFileToUrl: uploadFileToUrl
}
}
}());
我的问题是 - 如果我提到 onprogress 事件
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
文件上传没有任何问题,但 onprogress 事件仅在上传完成时触发一次。
我发现,为了避免这个问题,我必须使用 upload.onprogress。所以我将代码更改为
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete);
}
};
当我执行这个时,我得到错误-
XMLHttpRequest 无法加载 http://192.168.xxx.xxx:6152/api/UploadFile。预检响应具有无效的 HTTP 状态代码 405。
请帮我解决这个问题。
问题与 CORS 有关。我通过从 Nuget 安装 "CORS" 然后将以下代码添加到 WebApi.config 文件
从服务器端修复了它 var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
这解决了我的问题。