我想在将图像上传到服务器之前预览图像。我正在使用下面的脚本。相同的脚本在独立的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>
答案 0 :(得分:0)
您只能使用文件api执行此操作:
将其添加到预览功能的正确位置:
var reader = new FileReader();
reader.onload = (function(globalPic) { return function(e) { globalPic.src = e.target.result; }; })(globalPic);
reader.readAsDataURL(what.files[0]);