0

Here I am doing a Hybrid Android app conversion. My page is HTML page. I need to upload multiple images using Javascript only. In my page I can't use PHP if(isset($_POST['submit'])) function because it's a HTML page. And also I can't use <form action='upload.php' method='POST'>, because it redirect to that PHP page. So I can't be in a same page.

<form method="POST" action="" id="proinsert" name="proinsert" enctype="multipart/form-data">
<input type="file" name="photo" id="photo" class="form-control"> 
<button id="submit" name="submit" class="btn btn-primary margintop">Submit</button>
</form>

and my PHP page

foreach($_FILES['photos']['name'] as $file){ 
    $message .= "Attachments:" .$file['filename']; 
} 
Dave
  • 5,108
  • 16
  • 30
  • 40
Ranjith Kumar
  • 171
  • 3
  • 21

1 Answers1

0

Your question is very broad. However, I'll do my best to answer it:

You have 3 logical layers to your problem here:

  1. The HTML that creates the user interface
  2. The Javascript - that handles processing and sending your images (or any file) to another place.
  3. Your PHP code, which will accept your images and process/save them to your server.

A brief overview of how to approach the solution:

Build a form in HTML with a file upload field.

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

In your HTML file, write or include Javascript that will serialise the form data, and POST it to your PHP file.

<script type="text/javascript">
    const url = 'process.php';
    const form = document.querySelector('form');

    form.addEventListener('submit', e => {
        e.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);
        }

        // Uses browser's built in Fetch API - you can replace this with jQuery or whatever you choose.
        fetch(url, {
            method: 'POST',
            body: formData
        }).then(response => {
            console.log(response);
        });
    });
</script>

Write the logic into a new PHP file (called process.php) to handle the form data (images) as appropriate.

<?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']);

        $fileNames = [];
        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(end(explode('.', $_FILES['files']['name'][$i])));
            $fileNames[] = $file_name;

            $file = $path . $file_name;

            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 (empty($errors)) {
                move_uploaded_file($file_tmp, $file);
            }
        }

        if ($errors) {
            print_r($errors);
        } else {
            print_r(json_encode(['file_names' => $fileNames]));
        }
    }
}

For speed - the example code in this solution was taken from https://www.taniarascia.com/how-to-upload-files-to-a-server-with-plain-javascript-and-php/

For other examples - you could check out StackOverflow's other questions. Here's a similar one to yours: uploading image using javascript

Alex Mulchinock
  • 2,119
  • 1
  • 18
  • 25
  • Awesome Awesome...... In here I have only one doubt... How can I get the uploaded file name through alert??????????? – Ranjith Kumar Feb 26 '19 at 18:05
  • See the code above - $file_name = $_FILES['files']['name'][$i]; – Alex Mulchinock Feb 26 '19 at 18:07
  • See updated example - the response from the PHP script will now include an array of file names uploaded. You can access it from your Javascript like this: .then(response => { console.log(response.file_names) }) – Alex Mulchinock Feb 26 '19 at 18:15
  • fetch(url, { method: 'POST', body: formData }).then(response => { console.log(response.file_names) }); like this i am giving.. but no output – Ranjith Kumar Feb 26 '19 at 18:42
  • Sorry- my mistake. Do just console.log(response) and see what is there. file_names may be nested under another property. So it might be something like console.log(response.data.file_names) – Alex Mulchinock Feb 26 '19 at 19:07
  • Uncaught (in promise) TypeError: Cannot read property 'file_names' of undefined at fetch.then.response it shows like this dude........ – Ranjith Kumar Feb 26 '19 at 19:09
  • I’ll have to come back to you later. Not at a computer at the moment. – Alex Mulchinock Feb 26 '19 at 19:10