Mi función javascript solo carga los archivos de texto correctamente. ¿Alguien puede ayudarme a descubrir cómo hacer que también acepte imágenes, etc.?Javascript no está cargando datos binarios
function fileUpload(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
//Set vars
var file = files[i],
fileName = file.name,
fileSize = file.size,
fileData = file.getAsBinary(),
boundary = "xxxxxxxxx",
uri = "receive.php",
//Create file info HTML output
li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = file.name + ": " + file.size + " bytes";
li.appendChild(info);
//Start sending file
var xhr = new XMLHttpRequest();
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
if (xhr.responseText != "") {
alert(xhr.responseText); // display response.
}
}
}
}
var body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + fileName + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += fileData + "\r\n";
body += "--" + boundary + "--";
xhr.send(body);
}
fileList.appendChild(list);
return true;
}
}
Actualización: He encontrado la siguiente función en línea en http://code.google.com/p/html5uploader/ pero no puedo encontrar la manera de aplicarlo a mi función actual. ¿Es xhr.sendAsBinary lo único que cambió?
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
var boundary = 'xxxxxxxxx';
var body = '--' + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += bin + "\r\n";
body += '--' + boundary + '--';
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
// Firefox 3.6 provides a feature sendAsBinary()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
*snip*
¿cómo puede recuperar los archivos. Quiero decir que el parámetro de archivo debe proporcionarse en alguna parte. ¿Cómo haces eso? Necesito una pequeña explicación sobre este tema de carga de archivos a través de ajax. Cualquier ayuda será apreciada. – user1575229
@ user1698985 No estoy seguro de lo que quieres decir, ¿te refieres a recuperarlo en el lado de PHP? En ese caso, puede encontrarlo en los datos POST. – natli
recuperarlo del lado del servidor es otra discusión. Solo quiero encontrar la forma en que se selecciona el archivo en el cliente cargado en los datos de formularios y enviado a través de ajax. En Html5 es fácil. pero no entiendo cómo es en versiones anteriores de html. Traté de echar un vistazo al plugin ajaxform pero es difícil de entender cómo está recuperando los datos del archivo y enviándolos a través de ajax. Quiero entender todo el procedimiento, desde la selección del archivo hasta la gestión en jquery y enviarlo al servidor. – user1575229