Created
August 6, 2019 06:03
-
-
Save parzibyte/60a803fefb054c92a892ec989d31d035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="es"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Subida de múltiples archivos con AngularJS y FormData</title> | |
<script type="text/javascript" src="angular.min.js"></script> | |
</head> | |
<body ng-app="app"> | |
<div ng-controller="principal"> | |
<input id="archivos" multiple type="file"> | |
<br><br> | |
<input ng-model="nombre" type="text" placeholder="Tu nombre"> | |
<button ng-click="enviarFormulario()">Enviar</button> | |
</div> | |
<script> | |
/** | |
Envío de múltiples archivos y datos | |
a PHP desde AngularJS usando FormData y $http | |
@author parzibyte | |
parzibyte.me/blog | |
*/ | |
angular.module("app", []) | |
.controller("principal", ["$scope", "$http", function ($scope, $http) { | |
const $archivos = document.querySelector("#archivos"); | |
$scope.enviarFormulario = function () { | |
let archivos = $archivos.files; | |
if (archivos.length > 0 && $scope.nombre) { | |
let formdata = new FormData(); | |
// Agregar cada archivo al formdata | |
angular.forEach(archivos, function (archivo) { | |
formdata.append(archivo.name, archivo); | |
}); | |
// Finalmente agregamos el nombre | |
formdata.append("nombre", $scope.nombre); | |
// Hora de enviarlo | |
// Primero la configuración | |
let configuracion = { | |
headers: { | |
"Content-Type": undefined, | |
}, | |
transformRequest: angular.identity, | |
}; | |
// Ahora sí | |
$http | |
.post("./guardar_archivos.php", formdata, configuracion) | |
.then(function (respuesta) { | |
console.log("Después de enviar los archivos, el servidor dice:", respuesta.data); | |
}) | |
.catch(function (detallesDelError) { | |
console.warn("Error al enviar archivos:", detallesDelError); | |
}) | |
} else { | |
alert("Rellena el formulario y selecciona algunos archivos"); | |
} | |
}; | |
}]); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment