我不明白为什么javascript不能调用ftp?为什么我们要使用服务器发出这样的请求呢?
甚至浏览器也能够对ftp服务器进行身份验证和浏览。也许是用浏览器api来做的?
发布于 2016-06-07 08:45:53
JavaScript在http://ftp.apixml.net/有一个库,允许通过JavaScript上传文件。
在这种情况下,从技术上讲,ftpjs服务器正在与FTP服务器建立FTP连接,但是指令是通过JavaScript传递的。因此,这个特定的库主要是为了允许开发人员在不编写服务器端代码的情况下添加基本的文件上传机制。
在幕后,它使用HTML5 FileReader将文件读入base64字符串,然后使用CORS AJAX将其发布回服务器。
// Script from http://ftp.apixml.net/
// Copyright 2017 http://ftp.apixml.net/, DO NOT REMOVE THIS COPYRIGHT NOTICE
var Ftp = {
createCORSRequest: function (method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
},
upload: function(token, files) {
var file = files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.addEventListener("load",
function() {
var base64 = this.result;
var xhr = Ftp.createCORSRequest('POST', "http://ftp.apixml.net/upload.aspx");
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
Ftp.callback(file);
}
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("token=" + token + "&data=" + encodeURIComponent(base64) + "&file=" + file.name);
},
false);
},
callback: function(){}
};
https://stackoverflow.com/questions/26946684
复制相似问题