JavaScript图像上传和显示 [英] Javascript image upload and display

查看:69
本文介绍了JavaScript图像上传和显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本任务是选择图像并显示它,而不将其保存在数据库中.

My basic task is select image and display it,without saving it in database.

为此

1.我在html中创建了一个选择标签,可以通过该标签上传图片.

1.I have made a select tag in html,through which I can upload the image.

2.我制作了一个空白图像标签,其中没有图像源,或者是上载图像.

2.I have made a blank image tag in which at there is no image source,alternate is upload image.

3.select标记具有onchange javascript事件处理函数,该事件处理函数调用javascript函数changeimage.

3.select tag has onchange javascript event handler which calls javascript function changeimage.

<script>
       function changeimage()
       {
            document.form_name.imagetag.src=document.form_name.filetag.value;
       }
</script>

在上面的代码中

form_name:我的表单的名称

form_name : Is the name of my form

<form name = "form_name">

imagetag:是我的Img标签的名称

imagetag : Is the name of my Img tag

<Img src=" " name = "imagetag">

filetag:是我的名字

filetag : Is the name of my

<input type="file" name = "filetag" onchange="changeimage()">

我已经使用php扩展名保存了文件.当我尝试打印filetag的值时,它显示"C:\ fakepath \ image.png",为所有图像显示此地址. 我已经将我的php文件保存在www位置.

I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image. I have save my php file in www location.

我正在使用窗口7,wamp服务器和chrome最新版本.

I am using window 7,wamp server and chrome latest version.

推荐答案

您可能想签出此解决方案(其中我的代码源自).它涉及一些jQuery,但是如果您确实必须使用纯JS编写它,那么就可以了.

You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.

注意:我修改了您的代码以使其符合以下JS.另外,请尽量避免编写任何内联脚本.始终使您的HTML和JS保持松散耦合总是很好.

Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.

var fileTag = document.getElementById("filetag"),
    preview = document.getElementById("preview");
    
fileTag.addEventListener("change", function() {
  changeImage(this);
});

function changeImage(input) {
  var reader;

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

    reader.onload = function(e) {
      preview.setAttribute('src', e.target.result);
    }

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

<input type="file" id="filetag">
<img src="" id="preview">

这篇关于JavaScript图像上传和显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆