자바 스크립트로 업로드하기 전에 이미지 너비와 높이를 확인하세요.
사용자가 이미지를 넣을 수있는 양식이있는 JPS가 있습니다.
<div class="photo">
<div>Photo (max 240x240 and 100 kb):</div>
<input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>
이 js를 작성했습니다.
function checkPhoto(target) {
if(target.files[0].type.indexOf("image") == -1) {
document.getElementById("photoLabel").innerHTML = "File not supported";
return false;
}
if(target.files[0].size > 102400) {
document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
return false;
}
document.getElementById("photoLabel").innerHTML = "";
return true;
}
파일 유형과 크기를 확인하는 데 잘 작동합니다. 이제 이미지 너비와 높이를 확인하고 싶지만 할 수 없습니다.
나는 시도 target.files[0].width
했지만 나는 얻는다 undefined
. 다른 방법으로 0
.
어떤 제안?
파일은 파일 일 뿐이므로 다음과 같이 이미지를 만들어야합니다.
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
데모 : http://jsfiddle.net/4N6D9/1/
이것이 몇 가지 브라우저에서만 지원된다는 것을 알고 있습니다. 대부분 파이어 폭스와 크롬은 지금 쯤이면 오페라가 될 수 있습니다.
PS URL.createObjectURL () 메서드가 MediaStream 인터페이스에서 제거되었습니다. 이 메서드는 2013 년에 더 이상 사용되지 않으며 HTMLMediaElement.srcObject에 스트림을 할당하여 대체되었습니다. 이전 메소드는 덜 안전하기 때문에 제거되었으며 스트림을 종료하려면 URL.revokeOjbectURL ()을 호출해야합니다. 다른 사용자 에이전트는이 기능을 더 이상 사용하지 않거나 (Firefox) 제거 (Safari)했습니다.
나는 동의한다. 일단 사용자의 브라우저가 액세스 할 수있는 곳에 업로드되면 크기를 쉽게 알 수 있습니다. 이미지가로드 될 때까지 기다려야 onload
하므로 img
.
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
제 생각에 당신이 요구하는 완벽한 대답은
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
입력 유형 파일 / onchange = "validateimg (this)" 의 onchange 메소드에 함수를 첨부하십시오./
function validateimg(ctrl) {
var fileUpload = ctrl;
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (height < 1100 || width < 750) {
alert("At least you can upload a 1100*750 photo size.");
return false;
}else{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
function validateimg (ctrl) {
var fileUpload = $("#txtPostImg")[0];
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
console.log(this);
if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
alert("Height and Width must not exceed 1100*800.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
function uploadfile(ctrl) {
var validate = validateimg(ctrl);
if (validate) {
if (window.FormData !== undefined) {
ShowLoading();
var fileUpload = $(ctrl).get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
fileData.append('username', 'Wishes');
$.ajax({
url: 'UploadWishesFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function(result) {
var id = $(ctrl).attr('id');
$('#' + id.replace('txt', 'hdn')).val(result);
$('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();
HideLoading();
},
error: function(err) {
alert(err.statusText);
HideLoading();
}
});
} else {
alert("FormData is not supported.");
}
}
'program tip' 카테고리의 다른 글
Emacs에서 전체적으로 키 바인딩 무시 (0) | 2020.08.23 |
---|---|
Ruby를 사용하여 한 단계로 배열을 초기화하는 방법은 무엇입니까? (0) | 2020.08.23 |
Rails에서 문제를 테스트하는 방법 (0) | 2020.08.23 |
Tensorflow에서 그래프의 모든 Tensor 이름을 가져옵니다. (0) | 2020.08.23 |
FileUpload 서버 컨트롤을 사용하지 않고 ASP.net에서 파일 업로드 (0) | 2020.08.23 |