Javascript загрузить файл

Upload File to Server using PHP

The file is called by the Ajax request to handles the file upload process with PHP.

  • Retrieve the file information from posted data using the PHP $_FILES method.
  • Upload the file to the server using move_uploaded_file() function in PHP.
  • Render file upload status that returns to the Ajax success function.
<?php $upload = 'err'; if(!empty($_FILES'file'])){          // File upload configuration     $targetDir = "uploads/";     $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif');          $fileName = basename($_FILES'file']);     $targetFilePath = $targetDir.$fileName;          // Check whether file type is valid     $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);     if(in_array($fileType, $allowTypes)){         // Upload file to the server         if(move_uploaded_file($_FILES'file'], $targetFilePath)){             $upload = 'ok';         }     } } echo $upload; ?>

File Upload Form with Progress Bar

The file handles the file selection and live upload progress display operations.

File Upload Form:1. Create an HTML form with a file input field and a submit button.

  • The <form> tag must contain the attributes.
  • The <input> tag must contain .
<form id="uploadForm" enctype="multipart/form-data">
    <label>Choose File:</label>
    <input type="file" name="file" id="fileInput">
    <input type="submit" name="submit" value="UPLOAD"/>
</form>

2. Define an HTML element to display the progress bar.

<div class="progress">
    <div class="progress-bar"></div>
</div>

3. Define an HTML element to display the file upload status.

<div id="uploadStatus"></div>

Ajax File Upload with Progress Bar:
The jQuery and Ajax is used to upload file with a progress bar, so include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The following jQuery code sends the selected file data to the server-side script without reloading the page via Ajax.

  • On form submission, the selected file data is sent to the server-side script () using jQuery and Ajax.
    • The option of the method is used to track the upload progress.
    • The method creates a new XMLHttpRequest object.
    • The event of XMLHttpRequest property indicates the amount of progress made so far.
    • The upload progress percentage is attached to the progress bar.
  • The FormData object is used to retrieve the submitted file data.
  • On change event, the file type is validated based on the allowed types.
    • The File API is used to get the type of the selected file.
    • The MIME type of the selected file is validated and restricts the user to upload only the image (.jpeg/.jpg/.png/.gif) or PDF (.pdf) or MS Word (.doc/.docx) file.
    • The method determines whether allowedTypes array contains the selected file type.
<script>
$(document).ready(function(){
    
    $("#uploadForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = ((evt.loaded / evt.total) * 100);
                        $(".progress-bar").width(percentComplete + '%');
                        $(".progress-bar").html(percentComplete+'%');
                    }
                }, false);
                return xhr;
            },
            type: 'POST',
            url: 'upload.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $(".progress-bar").width('0%');
                $('#uploadStatus').html('<img src="images/loading.gif"/>');
            },
            error:function(){
                $('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
            },
            success: function(resp){
                if(resp == 'ok'){
                    $('#uploadForm')[].reset();
                    $('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
                }else if(resp == 'err'){
                    $('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
                }
            }
        });
    });
	
    
    $("#fileInput").change(function(){
        var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
        var file = this.files[];
        var fileType = file.type;
        if(!allowedTypes.includes(fileType)){
            alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).');
            $("#fileInput").val('');
            return false;
        }
    });
});
</script>

Отступать

Когда HTML5 не поддерживается (без File API ), единственным другим решением на чистом JavaScript (без Flash или любого другого плагина для браузера) является метод скрытого iframe , который позволяет имитировать асинхронный запрос без использования объекта XMLHttpRequest .

Он состоит из установки iframe в качестве цели формы с входными данными файла. Когда пользователь отправляет запрос, выполняется загрузка файлов, но ответ отображается внутри iframe вместо повторного рендеринга главной страницы. Скрытие iframe делает весь процесс прозрачным для пользователя и имитирует асинхронный запрос.

Если все сделано правильно, он должен работать практически в любом браузере, но у него есть некоторые предостережения относительно того, как получить ответ от iframe.

В этом случае вы можете предпочесть использовать плагин-оболочку, такой как Bifröst, который использует технику iframe, но также предоставляет транспорт jQuery Ajax, позволяющий отправлять файлы с помощью только такого метода:

Conclusion

The progress bar provides and user-friendly way of showing the upload completion status in real-time. You can add the jQuery progress bar to file upload and display percentage progress bar while the file is uploading to the server. The progress bar can be added to any type of file upload (image, pdf, doc, docx, audio, video, etc) in PHP. Our example code helps you to easily make the progress bar with percentage for upload, download, and installation operations.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Обновление 2019: это по- прежнему зависит от браузеров, которые использует ваша демографическая группа.

При использовании «нового» API HTML5 важно понимать, что он не поддерживался до IE 10. Если конкретный рынок, на который вы нацелены, имеет склонность к более старым версиям Windows выше среднего, у вас может не быть к нему доступа

По состоянию на 2017 год около 5% браузеров относятся к IE 6, 7, 8 или 9. Если вы направитесь в большую корпорацию (например, это инструмент B2B или что-то, что вы предлагаете для обучения), это число может резко возрасти. В 2016 году я имел дело с компанией, использующей IE8 на более чем 60% своих компьютеров.

На момент этой правки 2019 год, спустя почти 11 лет после моего первоначального ответа. IE9 и ниже глобально находятся на отметке 1%, но все еще есть группы с более высоким использованием.

Важный вывод из этого — какой бы ни была функция — проверьте, какой браузер используют ваши пользователи . Если вы этого не сделаете, вы быстро и болезненно усвоите урок, почему «работает для меня» недостаточно для доставки клиенту

caniuse — полезный инструмент, но обратите внимание, откуда они взяли свои демографические данные. Они могут не совпадать с вашими

Это никогда не бывает более справедливым, чем в корпоративных средах.

Мой ответ от 2008 года следует.

Однако существуют жизнеспособные методы загрузки файлов, отличные от JS. Вы можете создать на странице iframe (который вы скрываете с помощью CSS), а затем настроить таргетинг на свою форму для публикации в этом iframe. Главную страницу перемещать не нужно.

Это «настоящий» пост, поэтому он не полностью интерактивен. Если вам нужен статус, вам нужно что-то на стороне сервера, чтобы его обработать. Это сильно зависит от вашего сервера. ASP.NET имеет более приятные механизмы. Простой PHP не работает, но вы можете использовать модификации Perl или Apache, чтобы обойти это.

Если вам нужно несколько загрузок файлов, лучше загружать каждый файл по одному (чтобы преодолеть максимальные ограничения загрузки файлов). Опубликуйте первую форму в iframe, следите за ее продвижением, используя вышеуказанное, и когда она будет завершена, опубликуйте вторую форму в iframe и т. Д.

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Люкс-хост
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: