Skip to content Skip to sidebar Skip to footer

How to Upload Pictures Through Get Function Javascript

Writing the code to upload images to a server from scratch seems similar a very daunting task. I'g going to brand a very uncomplicated upload class to demonstrate how file information works and tin exist transferred.

In this tutorial, we're going to build an upload form with HTML, send the files with JavaScript, and process and upload them with PHP.

Note that this is not meant to exist fully functional, secure, validated, production lawmaking. It is simply meant to demonstrate in a uncomplicated and straightforward manner how to make your offset upload course.

  • View Source on GitHub

Prerequisites

  • A basic cognition of HTML
  • A bones knowledge of PHP syntax and code structure
  • An agreement of local PHP environments. If you lot don't know what that ways, please read this guide on how to ready a MAMP environment.

Goals

  • Build the simplest possible class with HTML to take a call back files from your local computer.
  • Send the data from an HTML form to a PHP script with vanilla JavaScript.
  • Process the data in the PHP script and motion the local files to an uploads/ directory on a server.

Setup

As mentioned in the prerequisites, you must have a bones cognition of PHP and local server environments.

If you already know how to use PHP and local environments, skip to the adjacent section.

If you're using a Mac, you can create a server with a unmarried command. To test this, create a file called test.php in the directory of your choice. I'thousand going to create a directory called local. The full path will be Users/tania/local.

examination.php

                                          <?php                repeat                'This is only a examination.'                ;                                    

In the Last application, which I'll open by pressing SPACEBAR + COMMAND and typing Last, navigate to the directory you created your file in.

Y'all should now be able to get to http://localhost:8888/examination.php and see the output of the code.

Screen Shot 2018 04 26 at 3 50 21 PM

If you're on Windows, or you don't want to use the command line, set up MAMP.

Building an Upload Form in HTML

In the root of your local server, create an alphabetize.html file. We'll just create a quick skeleton.

                                          <!                DOCTYPE                html                >                                                              <html                lang                                  =                  "en"                                >                                                              <head                >                                                              <meta                charset                                  =                  "UTF-8"                                />                                                              <meta                name                                  =                  "viewport"                                content                                  =                  "width=device-width, initial-calibration=1.0"                                />                                                              <meta                http-equiv                                  =                  "X-UA-Compatible"                                content                                  =                  "ie=edge"                                />                                                              <title                >              Upload Files                                  </title                >                                                              </caput                >                                                              <body                >                            <!-- class goes here-->                                                </body                >                                                              </html                >                                    

Let'due south add an HTML web grade to the body.

                                                            <form                method                                  =                  "post"                                enctype                                  =                  "multipart/form-information"                                >                                                              <input                type                                  =                  "file"                                name                                  =                  "files[]"                                multiple                />                                                              <input                type                                  =                  "submit"                                value                                  =                  "Upload File"                                name                                  =                  "submit"                                />                                                              </form                >                                    

In this form, we're using the Post HTTP method, which how we send information. The multipart/form-data value is required for uploading files in forms.

From here, we're creating a file input type that takes an array of files (files[]) and we're specifying multiple to allow more than one file to exist selected. files[] tin have any proper name - you could use uploads[] or images[], but I called it files[] for simplicity.

Finally, nosotros have a submit button. Since the adjacent step will be to add a script, permit's simply add a link to the JavaScript file nosotros'll create.

                                                            <script                src                                  =                  "upload.js"                                >                                                                            </script                >                                    

And that's all nosotros need for the view.

index.html

                                          <!                DOCTYPE                html                >                                                              <html                lang                                  =                  "en"                                >                                                              <head                >                                                              <meta                charset                                  =                  "UTF-8"                                />                                                              <meta                name                                  =                  "viewport"                                content                                  =                  "width=device-width, initial-scale=one.0"                                />                                                              <meta                http-equiv                                  =                  "X-UA-Compatible"                                content                                  =                  "ie=edge"                                />                                                              <title                >              Upload Files                                  </title                >                                                              </caput                >                                                              <body                >                                                              <course                method                                  =                  "mail"                                enctype                                  =                  "multipart/course-data"                                >                                                              <input                type                                  =                  "file"                                proper name                                  =                  "files[]"                                multiple                />                                                              <input                type                                  =                  "submit"                                value                                  =                  "Upload File"                                name                                  =                  "submit"                                />                                                              </form                >                                                              <script                src                                  =                  "upload.js"                                >                                                                            </script                >                                                              </body                >                                                              </html                >                                    

Screen Shot 2018 04 26 at 4 12 29 PM

Sending Grade Information via JavaScript

Right now, clicking submit on the form doesn't go anywhere. Since nosotros don't take an action that leads to a URL, the form will just mail to itself past default. Since alphabetize.html is an html file, not a PHP file, no form processing can happen on this folio. Instead, we'll send the form to PHP through JavaScript.

Create a file called upload.js.

Beginning, let's define two variables - the URL where we want to send the data, and the DOM element for the class.

upload.js

                          // Define processing URL and form element              const              url              =              'procedure.php'              const              form              =              certificate.              querySelector              (              'class'              )                      

We're going to add an event listener to picket for the form being submitted, but we'll prevent the default activeness from firing.

                          // Listen for form submit              form.              addEventListener              (              'submit'              ,              (              e              )              =>              {              due east.              preventDefault              (              )              // ...              }              )                      

Permit's gather the files with the .files property, and begin a new FormData() interface.

                          // Assemble files and begin FormData              const              files              =              document.              querySelector              (              '[type=file]'              )              .files;              const              formData              =              new              FormData              (              )              ;              }              )              ;              // ...                      

For each file that has been submitted, append it to the files[] array.

                          // Suspend files to files array              for              (              let              i              =              0              ;              i              <              files.length;              i++              )              {              let              file              =              files[i]              formData.              append              (              'files[]'              ,              file)              }              // ...                      

Finally, use the built-in Fetch API to POST the information to the URL we specified. Print the response to the panel (for testing purposes).

                          fetch              (url,              {              method:              'POST'              ,              body:              formData,              }              )              .              then              (              (              response              )              =>              {              console.              log              (response)              }              )                      

Here is the completed upload.js.

upload.js

                          const              url              =              'process.php'              const              form              =              certificate.              querySelector              (              'form'              )              form.              addEventListener              (              'submit'              ,              (              e              )              =>              {              east.              preventDefault              (              )              const              files              =              document.              querySelector              (              '[type=file]'              )              .files              const              formData              =              new              FormData              (              )              for              (              let              i              =              0              ;              i              <              files.length;              i++              )              {              let              file              =              files[i]              formData.              append              (              'files[]'              ,              file)              }              fetch              (url,              {              method:              'Post'              ,              body:              formData,              }              )              .              then              (              (              response              )              =>              {              console.              log              (response)              }              )              }              )                      

At present - how tin can we test if all this information is going through properly? Permit's print out the file data.

Create a new file called procedure.php, and print out the contents of the superglobal array $_FILES, which will comprise the data for all our files.

process.php

Once you have this file, attempt uploading a few files through the form. I made a phplogo.png and testfile1.txt to test with, and uploaded the file.

In Developer Tools, under the Console, you should meet a response similar this:

Programmer Tools -> Console

                                                                                                                                                        Response              {              type:              "basic",   url:              "http://localhost:8888/process.php",   redirected: false,   status:              200,   ok: true, …              }                      

If y'all encounter status: 200, this means the file hit the proper URL and the URL exists.

Now in Programmer tools, click on the Network tab. Y'all should see the filename process.php. Click on the file, and click on Response. There, y'all should come across the output of print_r($FILES). Information technology will await something like this:

Developer Tools -> Network -> Response

                          [files]              =>              Array              (              [name]              =>              Assortment              (              [              0              ]              =>              phplogo.png              [              1              ]              =>              testfile1.txt              )              [type]              =>              Array              (              [              0              ]              =>              image/png              [              i              ]              =>              text/plain              )              [tmp_name]              =>              Assortment              (              [              0              ]              =>              /              private              /              var              /thirty              [              1              ]              =>              /              individual              /              var              /yyy              )              [error]              =>              Assortment              (              [              0              ]              =>              0              [              1              ]              =>              0              )              [size]              =>              Array              (              [              0              ]              =>              16610              [              one              ]              =>              12              )              )                      

Now we know the proper files, along with all their associated information, accept gone through. Success!

Processing Form Information with PHP

Now that nosotros're gathering all the files from the form and sending them to process.php with JavaScript, we have to move the file data with PHP.

Offset, we'll want to make sure the code only runs when a Mail service request hits the file.

process.php

                                          <?php                if                (                $_SERVER                [                'REQUEST_METHOD'                ]                ===                'POST'                )                {                // ...                }                                    

Nosotros besides want to make certain files have gone through.

                          if              (              isset              (              $_FILES              [              'files'              ]              )              )              {              // ...              }                      

Create a directory in the root of your project called uploads. This directory will need to have 755 permissions to accept incoming files.

At this point, we'll create an array for errors, set the path of the directory where uploads should go, and set the approved extensions.

                          $errors              =              [              ]              ;              $path              =              'uploads/'              ;              $extensions              =              [              'jpg'              ,              'jpeg'              ,              'png'              ,              'gif'              ]              ;                      

Since the user can upload multiple files, nosotros'll create an $all_files variable, go the number of files beingness uploaded, and make a for loop.

                          $all_files              =              count              (              $_FILES              [              'files'              ]              [              'tmp_name'              ]              )              ;              for              (              $i              =              0              ;              $i              <              $all_files              ;              $i              ++              )              {              // ...              }                      

Now, for each file we'll get the file name, temporary file data, type, size, and extension.

                          $file_name              =              $_FILES              [              'files'              ]              [              'name'              ]              [              $i              ]              ;              $file_tmp              =              $_FILES              [              'files'              ]              [              'tmp_name'              ]              [              $i              ]              ;              $file_type              =              $_FILES              [              'files'              ]              [              'blazon'              ]              [              $i              ]              ;              $file_size              =              $_FILES              [              'files'              ]              [              'size'              ]              [              $i              ]              ;              $file_ext              =              strtolower              (              stop              (              explode              (              '.'              ,              $_FILES              [              'files'              ]              [              'name'              ]              [              $i              ]              )              )              )              ;              $file              =              $path              .              $file_name              ;                      

At present we can ready a few rules for the files. If the file type in not in the approved list of extensions, or the file is too big, we'll add it to the error array. I ready a file size of two megabytes.

                          if              (              !              in_array              (              $file_ext              ,              $extensions              )              )              {              $errors              [              ]              =              'Extension not allowed: '              .              $file_name              .              ' '              .              $file_type              ;              }              if              (              $file_size              >              2097152              )              {              $errors              [              ]              =              'File size exceeds limit: '              .              $file_name              .              ' '              .              $file_type              ;              }                      

If at that place were no errors, we tin can go ahead and motion the file to the uploads folder with the move_uploaded_file command.

                          if              (              empty              (              $errors              )              )              {              move_uploaded_file              (              $file_tmp              ,              $file              )              ;              }                      

At present we can close out the for loop, and print out the errors. This will display for united states in the network tab we used before to see the output of $_FILES.

                          if              (              $errors              )              print_r              (              $errors              )              ;                      

Put it all together, and hither's procedure.php.

process.php

                                          <?php                if                (                $_SERVER                [                'REQUEST_METHOD'                ]                ===                'Post'                )                {                if                (                isset                (                $_FILES                [                'files'                ]                )                )                {                $errors                =                [                ]                ;                $path                =                'uploads/'                ;                $extensions                =                [                'jpg'                ,                'jpeg'                ,                'png'                ,                'gif'                ]                ;                $all_files                =                count                (                $_FILES                [                'files'                ]                [                'tmp_name'                ]                )                ;                for                (                $i                =                0                ;                $i                <                $all_files                ;                $i                ++                )                {                $file_name                =                $_FILES                [                'files'                ]                [                'name'                ]                [                $i                ]                ;                $file_tmp                =                $_FILES                [                'files'                ]                [                'tmp_name'                ]                [                $i                ]                ;                $file_type                =                $_FILES                [                'files'                ]                [                'type'                ]                [                $i                ]                ;                $file_size                =                $_FILES                [                'files'                ]                [                'size'                ]                [                $i                ]                ;                $file_ext                =                strtolower                (                cease                (                explode                (                '.'                ,                $_FILES                [                'files'                ]                [                'name'                ]                [                $i                ]                )                )                )                ;                $file                =                $path                .                $file_name                ;                if                (                !                in_array                (                $file_ext                ,                $extensions                )                )                {                $errors                [                ]                =                'Extension not immune: '                .                $file_name                .                ' '                .                $file_type                ;                }                if                (                $file_size                >                2097152                )                {                $errors                [                ]                =                'File size exceeds limit: '                .                $file_name                .                ' '                .                $file_type                ;                }                if                (                empty                (                $errors                )                )                {                move_uploaded_file                (                $file_tmp                ,                $file                )                ;                }                }                if                (                $errors                )                print_r                (                $errors                )                ;                }                }                                    

Now test it out. If you use the grade to upload some files, yous'll see them in the uploads binder. If you lot try to upload a file that's too big or of the wrong type, you lot'll see the errors in the Network response.

Conclusion

Congratulations, y'all've successfully created a functioning upload form. This is an exciting footling process if you've never successfully uploaded a file or used the $_FILES superglobal before.

The complete source is on GitHub.

  • View Source on GitHub

Notation that this is not a consummate, secure, production process. Here are a few things to have into consideration:

  • In that location is no JavaScript side validation. The user should be shown an error on the front end finish if their file is of the wrong type before they submit.
  • Dealing with mutiple files with the same proper noun.
  • This method of fault handling is only for the development process.

Thanks for reading. I can also brand one about uploading to Amazon S3 and/or DigitalOcean Spaces if in that location'due south interest.

macecarre1941.blogspot.com

Source: https://www.taniarascia.com/how-to-upload-files-to-a-server-with-plain-javascript-and-php/

Post a Comment for "How to Upload Pictures Through Get Function Javascript"