php 如何在上传前后预览图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16207575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:43:30  来源:igfitidea点击:

How to preview an image before and after upload?

phpjavascriptjqueryhtml

提问by JCChan

I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:

我要在表单中预览图像或照片,但它不起作用,HTML 代码如下所示:

<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
    <p><label for="image">Upload Image:</label>
    <input type="file" id="imageUpload"/></p>
    <p><button type="submit" class="button">Save</button></p>
        <div id="preview">
            <img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
        </div>
    </form>

and incorporated JS code/script below:

并在下面合并了 JS 代码/脚本:

<script type="text/jaavascript">
$(document).ready(function(){
    var thumb=$('#thumb');
    new AjaxUpload('imageUpload',{
    action:$('newHotnessForm').attr('action'),
    name:'image',
    onSubmit:function(file,extension){
        $('#preview').addClass('loading');
    },
    onComplete:function(file,response){
        thumb.load(function(){
            $('#preview').removeClass('loading');
            thumb.unbind();
        });
        thumb.attr('src',response);
    }
    });
});

There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?

我的表单有两个主要问题:
1. 为什么图像或图片的预览不起作用?
2. 如何在单击保存按钮时粘贴表单中的照片,它将转到/链接到我创建的另一个 PHP 或 PHP 页面?

回答by Vijaya Pandey

Try this: (For Preview)

试试这个:(预览)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

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

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

工作演示在这里>

回答by Satinder singh

meVeekay's answer was good and am just making it more improvised by doing 2 things.

meVeekay 的回答很好,我只是通过做两件事让它更加即兴。

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

  1. 检查浏览器是否支持 HTML5 FileReader()。

  2. 通过检查其扩展名,只允许上传图像文件。

HTML :

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

详细了解 FileReader()

Check this Article : Using FileReader() preview image before uploading.

检查这篇文章:上传前使用 FileReader() 预览图像。

回答by ayan sil

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

回答by Merrin K

How to preview an image(For demonstration please click on the link below)

如何预览图像(演示请点击以下链接)

on input, type=file add an attribute onchange="preview()"

在输入时,type=file 添加一个属性 onchange="preview()"

For the function preview()type next line:

对于preview()下一行的函数类型:

thumb.src=URL.createObjectURL(event.target.files[0]);

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

现场示例:

var thumb = document.getElementById("view");

function preview() {

  thumb.src=URL.createObjectURL(event.target.files[0]);
  
}
div {
 margin-top:20px;
 color: rgba(0,0,0,.6);
 background: #6e6e6e;
 text-shadow: 3px 2px 3px rgba(255,255,255,.2);
}
<div>
  <input type="file" onchange="preview()">
  <img id="view" src="" />
</div>

Click this link to watch how it works https://youtu.be/7_lGhrYZJWw

单击此链接以观看其工作原理https://youtu.be/7_lGhrYZJWw

回答by Nischal Tyagi

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

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

    reader.readAsDataURL(input.files[0]);
  }
}
img {
  max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />