1

У меня получается 2 файла html файл и upload.php который грузит изображения в папку test. При успешной загрузке выводит сообщение "Файл загружен". Можно ли сделать чтобы это изображение сразу после загрузки на сервер выдергивалось и отображалось, без перезагрузки страницы. Добился только того что он может грузить и отображать сообщения

html:

<form action="upload.php" method="post" target="hiddenframe" enctype="multipart/form-data" onsubmit="hideBtn();">
<input type="file" id="userfile" name="userfile" />
<input type="submit" name="upload" id="upload" value="Загрузить" />
</form>
<div id="res"></div>
<iframe id="hiddenframe" name="hiddenframe" style="width:0px; height:0px; border:0px"></iframe>

JS:

function hideBtn(){
    $('#upload').hide();
    $('#res').html("Идет загрузка файла");
}

function handleResponse(mes) {
    $('#upload').show();
    if (mes.errors != null) {
        $('#res').html("Возникли ошибки во время загрузки файла: " + mes.errors);
    }   
    else {
        $('#res').html("Файл " + mes.name + " загружен");   
    }   
}

php:

<?php 

    if(isset($_POST['upload'])){
        //Список разрешенных файлов
        $whitelist = array(".gif", ".jpg", ".png");         
        $data = array();
        $error = true;

        //Проверяем разрешение файла
        foreach  ($whitelist as  $item) {
            if(preg_match("/$item\$/i",$_FILES['userfile']['name'])) $error = false;
        }

        //если нет ошибок, грузим файл
        if(!$error) { 

            $folder =  'test/';//директория в которую будет загружен файл

            $uploadedFile =  $folder.basename($_FILES['userfile']['name']);

            if(is_uploaded_file($_FILES['userfile']['tmp_name'])){

                if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadedFile)){

                    $data = $_FILES['userfile'];
                }
                else {  
                    $data['errors'] = "Во время загрузки файла произошла ошибка";
                }
            }
            else {  
                $data['errors'] = "Файл не  загружен";
            }
        }
        else{

            $data['errors'] = 'Вы загружаете запрещенный тип файла';
        }


        //Формируем js-файл    
        $res = '<script type="text/javascript">';
        $res .= "var data = new Object;";
        foreach($data as $key => $value){
            $res .= 'data.'.$key.' = "'.$value.'";';
        }
        $res .= 'window.parent.handleResponse(data);';
        $res .= "</script>";

        echo $res;

    }
    else{
        die("ERROR");
    }

    ?>
1
  • Устраивайте предпросмотр с помощью File API. 90% неверных файлов отсеивать у клиента. 10% оставшихся (которые пропатчат код клиента для проверки на уязвимость) упрутся в PHP.
    – user207618
    13 ноя 2016 в 9:25

1 ответ 1

1

Сделал вот так, добавив в существующий код:

js:

    function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#image').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}

$("#userfile").change(function(){
    readURL(this);
});

HTML:

<form name="" method="post" action="#" enctype="multipart/form-data" class="feedback-form-1">
                <fieldset>

                    <div class="input-file-row-1">

                        <div class="upload-file-container">
                            <img id="image" src="#" alt="" />                       
                            <div class="upload-file-container-text">
                            </div>
                        </div>              

                    </div>          
                </fieldset>
            </form>

CSS:

/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/* 
    Created on : 13.11.2016, 12:29:12
    Author     : Admin
*/


.input-file-row-1:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.input-file-row-1{
    display: inline-block;
    margin-top: 25px;
    position: relative;
}

html[xmlns] .input-file-row-1{
    display: block;
}

* html .input-file-row-1 {
    height: 1%;
}

.upload-file-container { 
    position: relative; 
    width: 100px; 
    height: 137px; 
    overflow: hidden;   
    background: url(http://i.imgur.com/AeUEdJb.png) top center no-repeat;
    float: left;
    margin-left: 23px;
} 

.upload-file-container:first-child { 
    margin-left: 0;
} 

.upload-file-container > img {
    width: 93px;
    height: 93px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

.upload-file-container-text{
    font-family: Arial, sans-serif;
    font-size: 12px;
    color: #719d2b;
    line-height: 17px;
    text-align: center;
    display: block;
    position: absolute; 
    left: 0; 
    bottom: 0; 
    width: 100px; 
    height: 35px;
}

.upload-file-container-text > span{
    border-bottom: 1px solid #719d2b;
    cursor: pointer;
}

.upload-file-container input  { 
    position: absolute; 
    left: 0; 
    bottom: 0; 
    font-size: 1px; 
    opacity: 0;
    filter: alpha(opacity=0);   
    margin: 0; 
    padding: 0; 
    border: none; 
    width: 70px; 
    height: 50px; 
    cursor: pointer;
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.