{"id":1612,"date":"2024-08-02T10:35:30","date_gmt":"2024-08-02T08:35:30","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1612"},"modified":"2024-08-02T10:35:31","modified_gmt":"2024-08-02T08:35:31","slug":"001-uploader-con-ajax-1","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/17-ejercicios-con-ajax\/001-uploader-con-ajax-1\/","title":{"rendered":"001. Uploader con Ajax (1)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">En este cap\u00edtulo vamos a hacer un <strong>uploader<\/strong>, y tan s\u00f3lo veremos la sintaxis de la subida de ficheros con la <strong>API<\/strong> de <strong>FETCH<\/strong>, lo subiremos del lado del servidor con PHP, en el siguiente cap\u00edtulo veremos como hacer la barra de progreso, y en otro siguiente hacerlo <strong>DRAG AND DROP<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p class=\"wp-block-paragraph\">Necesitamos tener instalado un <strong>servidor web<\/strong>, podemos instalar un <a href=\"https:\/\/www.apachefriends.org\/es\/index.html\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>XAMP<\/strong> <\/a>para tener un <strong>servidor web en modo local<\/strong>, lo pod\u00e9is bajar desde la siguiente URL.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.apachefriends.org\/es\/index.html\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.apachefriends.org\/es\/index.html<\/a><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">En este cap\u00edtulo vamos a ver un nuevo tipo de objeto que veremos en ejercicios donde est\u00e9n involucrados elementos de formulario. Podemos crear un objeto en <strong>Javascript<\/strong> denominado <strong><em>formData()<\/em><\/strong>, que veremos en el ejercicio de este cap\u00edtulo. <strong><em>formData()<\/em><\/strong> que puede recibir como par\u00e1metro un formulario.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Vamos a disponer de dos archivos, que tienen la siguiente sintaxis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis del archivo <em>uploader.html<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Uploader con AJAX&lt;\/title&gt;\n&nbsp; &nbsp; &lt;style&gt;\n&nbsp; &nbsp; &nbsp; html {\n&nbsp; &nbsp; &nbsp; &nbsp; box-sizing: border-box;\n&nbsp; &nbsp; &nbsp; &nbsp; font-family: sans-serif;\n&nbsp; &nbsp; &nbsp; &nbsp; font-size: 16px;\n&nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; *,\n&nbsp; &nbsp; &nbsp; *::after,\n&nbsp; &nbsp; &nbsp; *::before {\n&nbsp; &nbsp; &nbsp; &nbsp; box-sizing: inherit;\n&nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; main {\n&nbsp; &nbsp; &nbsp; &nbsp; display: flex;\n&nbsp; &nbsp; &nbsp; &nbsp; flex-direction: column;\n&nbsp; &nbsp; &nbsp; &nbsp; justify-content: center;\n&nbsp; &nbsp; &nbsp; &nbsp; align-items: center;\n&nbsp; &nbsp; &nbsp; &nbsp; text-align: center;\n&nbsp; &nbsp; &nbsp; &nbsp; min-height: 100vh;\n&nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &lt;\/style&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;main&gt;\n&nbsp; &nbsp; &nbsp; &lt;input type=\"file\" name=\"files\" id=\"files\" multiple \/&gt;\n&nbsp; &nbsp; &lt;\/main&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; const d = document,\n&nbsp; &nbsp; &nbsp; &nbsp; $main = d.querySelector(\"main\"),\n&nbsp; &nbsp; &nbsp; &nbsp; $files = d.getElementById(\"files\");\n&nbsp; &nbsp; &nbsp; \/\/ Creamos funci\u00f3n que mediante AJAX permita subir la carga de archivos\n&nbsp; &nbsp; &nbsp; \/\/ Esta funci\u00f3n se ejecutar\u00e1 por cada archivo que reciba el input\n&nbsp; &nbsp; &nbsp; const uploader = (file) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; const xhr = new XMLHttpRequest(),\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formData = new FormData();\n&nbsp; &nbsp; &nbsp; &nbsp; formData.append(\"file\", file);\n&nbsp; &nbsp; &nbsp; &nbsp; xhr.addEventListener(\"readystatechange\", (e) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (xhr.readyState !== 4) return;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let json = JSON.parse(xhr.responseText);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(json);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let message = xhr.statusText || \"Ocurri\u00f3 un error\";\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Error ${xhr.status}: ${message}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; &nbsp; xhr.open(\"POST\", \"uploader.php\");\n&nbsp; &nbsp; &nbsp; &nbsp; xhr.setRequestHeader(\"enc-type\", \"multipart\/form-data\");\n&nbsp; &nbsp; &nbsp; &nbsp; xhr.send(formData);\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; d.addEventListener(\"change\", (e) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; if (e.target === $files) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const files = Array.from(e.target.files);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; files.forEach((el) =&gt; uploader(el));\n&nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Sintaxis del archivo <em>uploader.php<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?php\nif(isset($_FILES[\"file\"])) {\n&nbsp; &nbsp; $name = $_FILES[\"file\"][\"name\"];\n&nbsp; &nbsp; $file = $_FILES[\"file\"][\"tmp_name\"];\n&nbsp; &nbsp; $error = $_FILES[\"file\"][\"error\"];\n&nbsp; &nbsp; $destination = \".\/files\/$name\";\n&nbsp; &nbsp; $upload = move_uploaded_file($file, $destination);\n\n&nbsp; &nbsp; if($upload) {\n&nbsp; &nbsp; &nbsp; &nbsp; $res = array(\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"err\" =&gt; false,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"status\" =&gt; http_response_code(200),\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"statusText\" =&gt; \"Archivo $name subido correctamente\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"files\" =&gt; $_FILES[\"file\"]\n&nbsp; &nbsp; &nbsp; &nbsp; );\n&nbsp; &nbsp; } else {\n&nbsp; &nbsp; &nbsp; &nbsp; $res = array(\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"err\" =&gt; true,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"status\" =&gt; http_response_code(400),\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"statusText\" =&gt; \"Error al subir el archivo $name\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \"files\" =&gt; $_FILES[\"file\"]\n&nbsp; &nbsp; &nbsp; &nbsp; );\n&nbsp; &nbsp; }\n&nbsp; &nbsp; echo json_encode($res);\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>En este cap\u00edtulo vamos a hacer un uploader, y tan s\u00f3lo veremos la sintaxis de la subida de ficheros con la API de FETCH, lo subiremos del lado del servidor con PHP, en el siguiente cap\u00edtulo veremos como hacer la barra de progreso, y en otro siguiente hacerlo DRAG AND DROP.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1609,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-1612","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En este cap\u00edtulo vamos a hacer un uploader, y tan s\u00f3lo veremos la sintaxis de la subida de ficheros con la API de FETCH, lo subiremos del lado del servidor con PHP, en el siguiente cap\u00edtulo veremos como hacer la barra de progreso, y en otro siguiente hacerlo DRAG AND DROP.","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1612","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1612"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1612\/revisions"}],"predecessor-version":[{"id":1614,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1612\/revisions\/1614"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1609"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1612"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}