사용자가 파일 업로드를 위해 파일을 선택했는지 확인하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/46219

  •  09-06-2019
  •  | 
  •  

문제

내가 가지고 있다면

<input id="uploadFile" type="file" />

태그 및 제출 버튼은 IE6(및 그 이상)에서 사용자가 파일을 선택했는지 어떻게 확인합니까?

FF에서는 다음을 수행합니다.

var selected = document.getElementById("uploadBox").files.length > 0;

하지만 IE에서는 작동하지 않습니다.

도움이 되었습니까?

해결책

이것은 IE(그리고 FF에서도 작동합니다):

if(document.getElementById("uploadBox").value != "") {
   // you have a file
}

다른 팁

이 코드는 내 로컬 환경에서 작동합니다. 라이브 환경에서도 작동하기를 바랍니다.

var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
    alert('Must Select any of your photo for upload!');
    nme.focus();
    return false;
}
function validateAndUpload(input){
    var URL = window.URL || window.webkitURL;
    var file = input.files[0];

    if (file) {
        var image = new Image();

        image.onload = function() {
            if (this.width) {
                 console.log('Image has width, I think it is real image');
                 //TODO: upload to backend
            }
        };

        image.src = URL.createObjectURL(file);
    }
};​

<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>

변경 시 이 함수를 호출하세요.

당신이 사용할 수있는:

    var files = uploadFile.files;

    if (files.length == 0) { console.log(true) } else { console.log(false) }
    if (files[0] == undefined) { console.log(true) } else { console.log(false) }
    if (files[0] == null) { console.log(true) } else { console.log(false) }

세 가지 모두 동일한 결과를 제공합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top