jquery 跨網域上傳檔案
HTML:
<input type="file" id="myfile" value="">
Javascript:
$("#myfile").change(function(){
var file = this.files[0];
t = $('meta[name=csrf-token]').attr('content');
var fd = new FormData();
var postUrl = "http://yoursites.com/utility/upload?authenticity_token="+ t +'&i=?';
fd.append('uploads', file);
var xhr = new XMLHttpRequest();
xhr.open('post', postUrl,true);
xhr.onload = function () {
data = JSON.parse(this.response); console.log(this.responseText);
};
xhr.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.send(fd);
});
<input type="file" id="myfile" value="">
Javascript:
$("#myfile").change(function(){
var file = this.files[0];
t = $('meta[name=csrf-token]').attr('content');
var fd = new FormData();
var postUrl = "http://yoursites.com/utility/upload?authenticity_token="+ t +'&i=?';
fd.append('uploads', file);
var xhr = new XMLHttpRequest();
xhr.open('post', postUrl,true);
xhr.onload = function () {
data = JSON.parse(this.response); console.log(this.responseText);
};
xhr.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.send(fd);
});
留言
張貼留言