簡體   English   中英

上傳前預覽圖像

[英]Preview an Image before Upload

我想在將圖像上傳到服務器之前預覽圖像。 我正在使用下面的腳本。 相同的腳本在獨立的 HTMl 中運行良好,但是當我在我的 jsp 中運行相同的腳本時,我的應用程序圖像已調整大小不會顯示。 任何幫助將不勝感激。

<script type="text/javascript">

// width to resize large images to
var maxWidth = 200;
// height to resize large images to
var maxHeight = 200;
// valid file types
var fileTypes = [ "bmp", "gif", "png", "jpg", "jpeg" ];
// the id of the preview image tag
var previewImage = "previewField";
// what to display when the image is not valid
var defaultPic = "spacer.gif";

var globalPic;
var extOk=false;


function preview(what) {

    var source = what.value;
    var imageName = source;
    var ext = source.substring(source.lastIndexOf(".") + 1, source.length).toLowerCase();
    for ( var i = 0; i < fileTypes.length; i++) {
        if (fileTypes[i] == ext) {
            extOk = true;
        }
    }
    if (extOk == true) {
        globalPic = new Image();
        imageName = imageName.replace(new RegExp(/\\/g),"/");
        globalPic.src ="file:///" + imageName;
        alert(globalPic.src);
        extOk = false;
        applyChanges();
    } else {
        alert(imageName);
        globalPic.src = defaultPic;
        alert("THAT IS NOT A VALID IMAGE\nPlease load an image with an extention of one of the following:\n\n"
                + fileTypes.join(", ") + "\n and not " + ext);
    }
}

function applyChanges() {


    var field = document.getElementById(previewImage);
    var x = parseInt(globalPic.width);
    var y = parseInt(globalPic.height);
    if (x > maxWidth) {
        y *= maxWidth / x;
        x = maxWidth;
    }
    if (y > maxHeight) {
        x *= maxHeight / y;
        y = maxHeight;
    }
    field.style.display = (x < 1 || y < 1) ? "none" : "";
    field.src = globalPic.src;
field.width = x;
    field.height = y;
}
</script>

您只能使用文件 api 執行此操作:

將此添加到您的預覽功能的正確位置:

var reader = new FileReader();  
reader.onload = (function(globalPic) { return function(e) { globalPic.src = e.target.result; }; })(globalPic);  
reader.readAsDataURL(what.files[0]);  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM