0

I have a form submit for file upload, with all the name transformation, filesize check, file extension check, etc.

I want to know, if there's some way to preupload the file before the submit, because in the submit, the upload is made and sometimes, if I need to upload a big file like 500mb, with a fast internet connection can be made so easy, but with a slow internet like mobile wifi, the petition expires the timeout and it's cancelled.

My idea is to configure a preupload when the file is attached, with a loading bar and a X to cancel the preupload, and not let the user click the submit form until the file is completely preupload, then the submit only takes a few seconds, moving the file in the temporary folder to the upload location.

Can someone explain me what type of language I need to use, the functions or code I need to write, or maybe some guides I can follow? I have been looking for information but I didn't find something usefull.

Edit: upload form code. Now the submit is automatic when the user drops/attaches the files, but it doesn't matter to the real question.

<button type="submit" class="btn btn-primary btn-xs" id="add_file" name="add_file" form="upload-form" style="display:none;">Subir archivos</button>
<form action="info_order.php?order=<?php echo $order; ?>" id="upload-form" method="post" enctype="multipart/form-data">
    <?php if((strpos($_SERVER['HTTP_USER_AGENT'],'Windows'))||(strpos($_SERVER['HTTP_USER_AGENT'],'Macintosh'))){ ?>
        <div id="dropzone" class="drop-zone" style="display:none;">
            <span class="drop-zone__prompt">Haga click o arrastre los archivos que desea subir.</span>
            <input type="file" name="file-upload[]" style="display:none;" id="file-upload" class="drop-zone__input" multiple>
        </div>
    <?php } elseif((strpos($_SERVER['HTTP_USER_AGENT'],'Android'))||(strpos($_SERVER['HTTP_USER_AGENT'],'iPhone'))){ ?>
            <input type="file" name="file-upload[]" id="file-upload2" style="display:none;" onchange="document.getElementById('add_file').click()" multiple>
            <button type="button" class="btn btn-primary" onclick="document.getElementById('file-upload2').click()">Subir archivos</button>
            </input>
        <?php } ?>
    </form>

POST submit code:

if(isset($_POST['add_file'])) { $error_message = ''; $ok = 0; $nook = 0; $new_value = '';
        $array_ext = array('pdf','docx','doc','xlsx','xls','xlsb','jpg','jpeg','png','mp3','mp4','msg','txt','zw1','7z','zip','psd','skr');
        if($_POST['admin-upload'] == true){ $access_level = 1; } else { $access_level = 2; }
        $total_count = count($_FILES['file-upload']['name']);
        for($i=0;$i<$total_count;$i++) {
            $filename = $_FILES['file-upload']['name'][$i];
            $tmpFilePath = $_FILES['file-upload']['tmp_name'][$i];
            $filename = str_replace("'","",strtolower($filename)); $filename = $order.'_'.$filename;
            if($filename != ''){
                $ext = strtolower(substr( $filename, strrpos( $filename, '.' ) + 1 ) );
                if(in_array($ext, $array_ext)) {
                    $upload_path = 'uploads/orders';
                    if(is_writable($tmpFilePath)){
                        $search_file = $upload_path.'/'.$filename;
                        if(file_exists($search_file)){
                            for($i=2;$i<999;$i++) {
                                $filename_noext = basename($filename,'.'.$ext);
                                $new_search_file = $upload_path.'/'.$filename_noext.'('.$i.').'.$ext;
                                if(!file_exists($new_search_file)){ $filename = $filename_noext.'('.$i.').'.$ext; break; }
                            }
                            $search_file = $new_search_file;
                        }
                        if(($info_order['Archivos adjuntos'] == "")&&($new_value == '')){ $new_value = $filename.'β'.$access_level; } elseif(($info_order['Archivos adjuntos'] != "")&&($new_value == '')){ $new_value = $info_order['Archivos adjuntos'].'α'.$filename.'β'.$access_level; } else { $new_value .= 'α'.$filename.'β'.$access_level; }
                        $update_date = strftime("%Y-%m-%d %H:%M:%S"); $tracking_date = strftime("%d/%m/%Y - %H:%M");
                        $newtrack = '#'.'<b>'.$tracking_date.'</b><br/>El usuario '.$name_user.' ha subido el fichero '.$filename.'.'; $tracking .= $newtrack;
                        $sql = "UPDATE `ordenes` SET `Archivos adjuntos` = '{$new_value}', `Fecha última modificación` = '{$update_date}', `Tracking` = '{$tracking}' WHERE `Nº orden` = '{$order}'";
                        if($db->query($sql)){
                            if(move_uploaded_file($tmpFilePath,$search_file)){
                                unset($tmpFilePath);
                                $error_message .= '<br/><li>El fichero '.$filename.' se ha subido correctamente.</li>'; $ok++;
                            } else {
                                $error_message .= '<br/><li>El fichero '.$filename.' no se pudo subir al directorio correctamente.</li>'; $nook++;
                            }
                        } else {
                            $error_message .= '<br/><li>El fichero '.$filename.' no se pudo agregar a la base de datos correctamente.</li>'; $nook++;
                        }
                    } else {
                        $error_message .= '<br/><li>El fichero no se puede subir porque no tiene permisos de escritura.</li>'; $nook++;
                    }
                } else {
                    $error_message .= '<br/><li>El fichero '.$filename.' no se puede subir porque la extensión no está permitida.</li>'; $nook++;
                }
            } else {
                $error_message .= '<br/><li>El fichero no se puede subir porque no tiene nombre.</li>'; $nook++;
            }
        }
        if($nook == 0){ $session->msg('s',$error_message); } elseif($ok == 0){ $session->msg('d',$error_message); } else { $session->msg('w',$error_message); }
        redirect('info_order.php?order='.$order);
    }

php.ini configuration php.ini

  • Does this answer your question? [File upload progress bar with jQuery](https://stackoverflow.com/questions/15410265/file-upload-progress-bar-with-jquery) – icecub Aug 18 '22 at 09:46
  • 3
    I don't see any benefit of that, the user will still have to wait for the " preupload " to finish. You need a multipart upload + a progress bar – Lk77 Aug 18 '22 at 09:47
  • Welcome! 1. Asking for suggestions/recommendations about libraries(languages/guides etc are unfortunately off-topic here. Read [What topics can I ask about here?](https://stackoverflow.com/help/on-topic) for more info. 2. The question is way too unfocused. SO is for when you get stuck on something _specific_ with your implementation. – M. Eriksson Aug 18 '22 at 09:47
  • And as others pointed out, uploading the file separately will have the same issues (timeouts etc). Wouldn't it also be annoying for the user to first choose file and then have to wait for it to be uploaded before they can submit the rest? – M. Eriksson Aug 18 '22 at 09:49
  • @Lk77 There is a benefit though. The user is able to see that the upload is in progress instead of staring at a blank screen not understand why it's still "loading". Other than that, the max upload file size will probably have to be adepted in the php.ini file as well as disabling the PHP timeout for handling it. – icecub Aug 18 '22 at 09:49
  • 1
    @icecub that benefit come from a progress bar, not from a " preupload " feature – Lk77 Aug 18 '22 at 09:51
  • True. I mean, preupload hardly makes sense at all. What if the upload is finished and the user decides to never submit at all? – icecub Aug 18 '22 at 09:51
  • 1
    Yeah i agree, it should be uploaded on submit, but using multipart and with a progress bar with percentages / upload speed and so on – Lk77 Aug 18 '22 at 09:53
  • @Lk77 can u explain me the multipart upload + progress bar? I paste you now a piece of code with the submit form and post, the bar is not the main problem, only a solution to show the user the upload progress. And as icecub said, the reason is to make the preupload to avoid the php timeout, preferring that the user waits in the preupload instead of the upload, but I can configure it as you can consider better. – leesin koreano Aug 18 '22 at 09:59
  • _"the reason is to make the preupload to avoid the php timeout"_ - but it doesn't avoid that, unless the rest of the form is massive. – M. Eriksson Aug 18 '22 at 10:04
  • You are already using multipart/form-data, so check if your server actually support it – Lk77 Aug 18 '22 at 10:06
  • fyi, PHP can do [Session Upload Progress](https://www.php.net/manual/en/session.upload-progress.php) (if you don't want to use JS) – brombeer Aug 18 '22 at 10:07
  • @Lk77 how can i check it? Maybe an upload progress bar like a modal during the upload can solve the problem, but I need to know how to read the progress upload information in real time (i guess with javascript or jquery) – leesin koreano Aug 18 '22 at 10:08
  • Do some research, like google: "add progress bar to ajax file upload" and you'll find many guides/tutorials. Go through a few and make some attempts. If you get stuck on something _specific_ along the way, come back, post the relevant code and explain the issue. You might need to add what ajax method you're using, like "with jQuery" or "with fetch" or similar. – M. Eriksson Aug 18 '22 at 10:09
  • Check the headers of the request in your browser network tab, you should have something like : Content-Range: bytes xx-yyyy/zzzz with multiple upload requests beeing sent – Lk77 Aug 18 '22 at 10:18
  • And also the response should have a header that looks like 'Range: x-y', if you don't have it, perhaps it's because your file is too small, try with a file bigger than 500m, it should chunk it. If it does not that means you will need to rework your backend code to manage multipart upload – Lk77 Aug 18 '22 at 10:27
  • @Lk77 I found one video on Internet, that makes everything I want, the only thing is that 8 years later, something has changed and I have to adapt it to work with it. https://www.youtube.com/watch?v=EraNFJiY0Eg – leesin koreano Aug 18 '22 at 11:57

0 Answers0