使用javascript上传图片 [英] Upload image using javascript

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

问题描述

我正在尝试将客户端的javascript图像作为对象来使用jQuery发送它

I'm trying to get image as Object of javascript on the client side to send it using jQuery

<html>
<body>
<script language="JavaScript">
function checkSize()
{
    im = new Image();
    im.src = document.Upload.submitfile.value;
if(!im.src)
    im.src = document.getElementById('submitfile').value;
    alert(im.src);
    alert(im.width);
    alert(im.height);
    alert(im.fileSize);

}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
   <p>Filename: <input type="file" name="submitfile" id="submitfile" />
   <input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>

但在此代码中只有 alert(im.src)正在显示 src 的文件,但是 alert(im.width),alert(im.height),alert(im.filesize)无法正常工作并提醒 0 0 undefined 分别。请告诉我如何使用javascript访问图像对象?

But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?

推荐答案

im.fileSize仅在IE中工作的原因是因为.fileSize只是一个IE属性。由于您的代码可以在IE中运行,我会检查浏览器并呈现您当前的IE代码并尝试其他浏览器。

The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.

var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
    var width;
    var height;
    var fileSize;
    var reader = new FileReader();
    reader.onload = function(event) {
        var dataUri = event.target.result,
        img = document.createElement("img");
        img.src = dataUri;
        width = img.width;
        height = img.height;
        fileSize = imgFile.files[0].size;
        alert(width);
        alert(height);
        alert(fileSize);
   };
   reader.onerror = function(event) {
       console.error("File could not be read! Code " + event.target.error.code);
   };
   reader.readAsDataURL(imgFile.files[0]);
}

我没有测试过这段代码但是只要我不这样做就应该有效有一些错字。为了更好地理解我在做什么,请查看链接

I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.

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

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