动态地​​显示图像

动态地​​显示图像

本文介绍了jQuery:如何使用“值"动态地​​显示图像<输入类型=“文件">的场地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以动态显示用户刚刚上传到输入type ="file"字段的图像.

I was wondering whether there is a way to dynamically display an image that a user just uploaded to the input type="file" field.

例如,到目前为止,我有以下代码:

For example, so far I have the following code:


image_upload.html

<form id ="image_upload_form" action="" method="post" enctype="multipart/form-data">
    <input id ="id_iamge" type="file" name="image" />
    <input type="submit" value="Upload" />
</form>

<div id="image_view">
    <img id="uploaded_image">
</div>


upload.js

$(document).ready(function() {
    $("#id_image").change(file_select);
});

function file_select(event) {
    $("#uploaded_image").attr("src", $("#id_image").val());
}


所以我基本上想显示用户刚刚在Field上上传的图像.

So I basically want to show the image that the user just uploaded on the Field.

当然,我知道如果用户已经提交了表单,并且该图像已经在我的数据库服务器中,那么我可以轻松查看该图像.

Of course, I know I can easily view the image if the user already SUBMITTED the form, and when the image is already inside my Database server.

但是,我想在将图像提交到数据库服务器之前预览图像.

However, I want to preview the image BEFORE the image is submitted into the database server.

为此,我想我必须在上载器自己的计算机中找出图像的路径,然后将本地路径"设置为图像的"src".

In order to do this, I guess I have to find out the PATH of the Image in the Uploader's own computer and then set that "Local path" as the "src" of the image.

是否可以获取用户刚刚提交的图像的本地路径?

Is there a way to fetch this LOCAL PATH of the image that the user just submitted?

(上面的Javascript代码显然不起作用,因为它只是将图像文件的名称(而不是绝对路径)设置为"src".例如,当我运行该代码并上传图像时,得到这个:

(My Javascript code above obviously didn't work, since it just sets the NAME of the image file, not the absolute Path, as the "src". For example, when I run that code and upload an image, I get this:

结果:

<img id="uploaded_image" src="random_image.jpg" />

什么也没显示.

推荐答案

看看这个示例,它应该可以工作: http://jsfiddle.net/LvsYc/

Take a look at this sample, this should work: http://jsfiddle.net/LvsYc/

HTML:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

JS:

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]);
    }
}

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

这篇关于jQuery:如何使用“值"动态地​​显示图像&lt;输入类型=“文件"&gt;的场地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:00