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']; 
} 
0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

Awesome Awesome...... In here I have only one doubt... How can I get the uploaded file name through alert???????????
See the code above - $file_name = $_FILES['files']['name'][$i];
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) })
fetch(url, { method: 'POST', body: formData }).then(response => { console.log(response.file_names) }); like this i am giving.. but no output
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)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.