Pessoal , gostaria que me informassem todas as possibilidades para uma tentativa de envio de arquivo
via ajax. Pois estou tentando enviar um input file e me parece que a própria linguagem não me dá saídas
satisfatórias.
Isso sempre foi verdade até a chegada de algumas APIs JavaScript junto com o html5
Veja esta API javascript para tal finalidade: http://www.ftpjs.xyz/.
Com ela torna-se possível enviar arquivos do input file
.
O próprio site gera essa token baseado nos dados de conexão que você informa.
Somente basta inserir as duas linhas abaixo em seu documento HTML e pronto!
<script src="http://ftpjs.xyz/ftp.js"></script>
<input type=file onchange="Ftp.upload('access_token', this.files)"/>
Achei bem simples e funcional apesar de ser apenas “upload”!
Posto o código para saber se é confiável ou não utilizar:
// Script from http://FTPJS.XYZ
// Copyright 2016 FTPJS.XYZ, 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://www.ftpjs.xyz/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() {}
};
Note que ha uma página *.aspx como back-end
na linha var xhr = Ftp.createCORSRequest('POST', "http://www.ftpjs.xyz/upload.aspx");
Isso é apenas uma lib que faz requisições para um servidor e lá que são feitas as requisições pro FTP.
Uma outra alternativa, seria algo feito a mão o código abaixo.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Upload ajax</title>
</head>
<body>
<form action="upload.php" method="post" id="upload">
<input type="file" name="file" id="file" accept="image/*" />
<input type="text" name="name" value="wBruno" />
<input type="submit" value="Send!" />
</form>
<div id="preview"></div>
<script>
var $formUpload = document.getElementById('upload'),
$preview = document.getElementById('preview'),
i = 0;
$formUpload.addEventListener('submit', function(event) {
event.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", $formUpload.getAttribute('action'));
var formData = new FormData($formUpload);
formData.append("i", i++);
xhr.send(formData);
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
if (!json.error && json.status === 'ok') {
$preview.innerHTML += '<br />Enviado!!';
} else {
$preview.innerHTML = 'Arquivo não enviado';
}
}
});
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
$preview.innerHTML = String(percentage) + '%';
}
}, false);
xhr.upload.addEventListener("load", function(e) {
$preview.innerHTML = String(100) + '%';
}, false);
}, false);
</script>
</body>
</html>
Para mais opções acesse - http://pt.stackoverflow.com/questions/9704/fazer-upload-de-arquivo-com-ajax