addEventListener 获取上传进度结果请求方式从 Post 变 Options 了?

2017-09-06 04:37:27 +08:00
 hard2reg

学习 js 中,不知道怎么改,google 也查不到相关的。。。多谢

$(function() {
	$("body").bind("dragover", function(ev) {
		ev.preventDefault();
		//console.log("dragover event was prevented");
	});
	$("body").bind("drop", function(ev) {
		ev.preventDefault();
		//console.log("drop event was prevented");
		var files = ev.originalEvent.dataTransfer.files;
		//console.log(files);
		for (file of files) {
			//console.log(`${file.name}  ${file.size} bytes`);
			if (!file.size) {
				console.log(`error: ${file.name} is an empty file`);
				continue;
			}
			if (file.type.indexOf("image") == -1) {
				console.log(`error: ${file.name} is a non-image file`);
				continue;
			}
			var fd = new FormData();
			fd.append("pic", file);
			//console.log(`uploading ${file.name} ...`);
			$.ajax({
				url: "https://xxxx.com/upload.php", 
				type: "POST", 
				data: fd, 
				processData: false, 
				contentType: false, 
				success: function(res) {
					console.log(res);
				}, 
				error: function(jqXHR) {
					console.log(jqXHR.responseText);
				}, 
				xhr: function() {
					myXHR = $.ajaxSettings.xhr();
					myXHR.upload.addEventListener("progress", function(e) {
						console.log(`${file.name}  uploaded ${e.loaded}`);
					});
					return myXHR;
				}
			});
		}
	});
});
4622 次点击
所在节点    JavaScript
14 条回复
hard2reg
2017-09-06 04:40:42 +08:00
@Livid 求删帖,不小心把 Post 地址贴上来了。。。
hard2reg
2017-09-06 04:41:35 +08:00
不用了。。还可以 edit。。。
hard2reg
2017-09-06 04:56:55 +08:00
php 开头已设置 Access-Control-Allow-Origin: *
leonlu
2017-09-06 08:08:08 +08:00
如果跨域了,chrome 是会先发个 options 问问能不能跨域的
hard2reg
2017-09-06 08:26:43 +08:00
@leonlu 是的,我先前不知道跨区域要 options,现在这个问题解决了。新的问题是。。xhr 中的 file.name 不正确。。如果我上传文件 a.jpg b.jpg c.jpg ,最后的输出结果都是 a.jpg uploaded xxx/xxxxx。
Kokororin
2017-09-06 08:52:09 +08:00
append 的第三个参数就是 filename
hard2reg
2017-09-06 09:16:21 +08:00
@Kokororin 不是服务端返回同样的文件名。我 js 中有调试输出,xhr:后面的 file.name 受循环影响啦。
Kokororin
2017-09-06 09:40:45 +08:00
@hard2reg #7 把 ajax 的代码放在一个闭包里,file.name 作为参数就可以了
Kokororin
2017-09-06 09:42:44 +08:00
@hard2reg #7 或者 for (let file of files)
hard2reg
2017-09-06 10:07:51 +08:00
@Kokororin let file of files? 还能这么写啊
hard2reg
2017-09-06 10:19:37 +08:00
@Kokororin 看了 Mozilla 的文档了解了一下 let,好像闭包传参的兼容性和可读性更好?
Kokororin
2017-09-06 12:50:54 +08:00
@hard2reg #11 http://caniuse.com/#search=let 可读性难道不是 let 更好吗,兼容性不是问题,过一下 babel
hard2reg
2017-09-06 16:31:28 +08:00
@Kokororin 哦哦,谢谢了。我在想想
hard2reg
2017-09-07 01:59:00 +08:00
@Kokororin 试了下文件名正常输出了,十分感谢!
```
jqXHR.upload.addEventListener("progress", function(ev) {
console.log(`ev.total ${ev.total} Size ${file.size}`);
});
```
输出结果显示:ev.total 获取到的字节数比 file.size 获取到的大一些,正常吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/388479

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX