我的网络表单上有Asp:FileUpload控件。
在 FileUpload 控件的 OnChange()事件中,执行JavaScript函数
<asp:FileUpload ID="fUpload" runat="server" Style="visibility: hidden;width:1px" onchange="callme(this)"/>
Javascript功能:
function callme(oFile) {
document.getElementById('<%=txtFilePath.ClientID%>').value = oFile.value;
ReadImage(oFile.value);
}
ReadImage函数应读取文件并告知所选文件的高度宽度和大小,如果文件不是图像,则显示错误消息。
function ReadImage(_file)
{
var reader = new FileReader();
var image = new Image();
image.src = 'file://' + _file;
image.onload = function() {
alert('Step 2');
var w = this.width,
h = this.height,
t = file.type,
n = file.name,
s = ~ ~(_file.size / 1024) + 'KB';
alert('<img src="' + this.src + '"> ' + w + 'x' + h + ' ' + s + ' ' + t + ' ' + n + '<br>');
};
image.onerror= function()
{
alert('Invalid file type: '+ _file.type);
};
}
ReadImage()函数应该读取所选文件,并在上传到服务器之前获取该文件的高度,宽度和大小。
如何做到这一点?我做错了什么。
答案 0 :(得分:0)
function callme(oFile)
{
document.getElementById('<%=txtFilePath.ClientID%>').value = oFile.value;
ReadImage(oFile);
}
function ReadImage(_file) {
var fr = new FileReader;
fr.onload = function () { // file is loaded
var img = new Image;
img.onload = function () {
alert('Step 2');
var w = img.width;
var h = img.height;
alert('<img src="' + fr.result + '"> ' + w + 'x' + h + '<br>'); // is the data URL because called with readAsDataURL
};
img.onerror = function () {
alert('Invalid file type');
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(_file.files[0]); // for using a <input type="file">
}
答案 1 :(得分:0)
我的问题的其余部分 - “上传前获取文件大小”
使用此javascript
function checkFile(fieldObj) {
var FileName = fieldObj.value;
var FileExt = FileName.substr(FileName.lastIndexOf('.') + 1);
var FileSize = fieldObj.files[0].size;
var FileSizeMB = (FileSize / 10485760).toFixed(2);
if ((FileExt != "png" && FileExt != "doc" && FileExt != "bmp" && FileExt != "dib" && FileExt != "JPG" && FileExt != "jpeg" && FileExt != "jpe" && FileExt != "jfif" && FileExt != "gif" && FileExt != "tiff" && FileExt != "tif" && FileExt != "tga") || FileSize > 10485760) {
var error = "File type : " + FileExt + "\n\n";
error += "Size: " + FileSizeMB + " MB \n\n";
error += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(error);
return false;
}
return true;
}
答案 2 :(得分:-1)
你没有尝试过image.src ='file://'+ _ file;
var img = new Image;
img.onload = function() {
alert(img.width);
alert(img.height);
};
img.onerror = function() {
alert("error");
};
img.src = oFile.value;