Programing

파일 업로드 크기 제한 (HTML 입력)

lottogame 2021. 1. 10. 16:43
반응형

파일 업로드 크기 제한 (HTML 입력)


사용자가 업로드 할 수있는 파일의 크기를 제한하고 싶습니다.

나는 maxlength = 20000 = 20k라고 생각했지만 전혀 작동하지 않는 것 같습니다.

PHP가 아닌 Rails에서 실행 중이지만 HTML / CSS에서 클라이언트 측을 수행하거나 jQuery를 사용하는 최후의 수단으로 수행하는 것이 훨씬 더 간단 할 것이라고 생각했습니다. 이것은 내가 빠졌거나 알지 못하는 HTML 태그가 있어야 할 정도로 매우 기본적인 것입니다.

IE7 +, Chrome, FF3.6 +를 지원하려고합니다. 필요한 경우 IE8 + 만 지원할 수 있다고 생각합니다.

감사.


클라이언트 측에서는 할 수 없습니다. 서버에서해야합니다.

편집 :이 답변은 구식입니다!

이 편집 당시 HTML 파일 API는 대부분 모든 주요 브라우저에서 지원됩니다 .

솔루션 업데이트를 제공하고 싶지만 @ mark.inman.winning이 이미 해냈습니다 .

이제 클라이언트에서 유효성을 검사 할 수있는 경우에도 서버에서 유효성을 검사해야합니다. 모든 클라이언트 측 유효성 검사를 우회 할 수 있습니다.


이것은 완전히 가능합니다. 자바 스크립트를 사용하세요.

jQuery를 사용하여 입력 요소를 선택합니다. 변경시 이벤트로 설정했습니다.

$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) { 

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
    $("#approvedFiles").val(approvedHTML);

});

The code above saves all the file names that I deem worthy of persisting to the submission page, before the submit actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server side we do have to filter these out. I haven't written any code for that yet, but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and match them to the $_FILES(PHP Superglobal, sorry I dont know ruby file variable) variable.

내 요점은 제출하기 전에 파일을 확인할 수 있다는 것입니다. 이 작업을 수행 한 다음 사용자가 양식을 제출하기 전에 사용자에게 출력하여 내 사이트에 무엇을 업로드하는지 알립니다. 기준을 충족하지 않는 것은 사용자에게 다시 표시되지 않으므로 너무 큰 파일은 저장되지 않는다는 사실을 알아야합니다. FormData 개체를 사용하지 않기 때문에 모든 브라우저에서 작동합니다.


var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

이 예제는 잘 작동합니다. 나는 대략 2MB로 설정했고, 1MB는 ​​1,048,576이므로 필요한 한도만큼 곱할 수 있습니다.

더 명확하게하기위한 jsfiddle 예제는 다음과 같습니다.
https://jsfiddle.net/7bjfr/808/


아래 코드 스 니펫을보세요 ↓

const input = document.getElementById('input')

input.addEventListener('change', (event) => {
  const target = event.target
  	if (target.files && target.files[0]) {

      /*Maximum allowed size in bytes
        5MB Example
        Change first operand(multiplier) for your needs*/
      const maxAllowedSize = 5 * 1024 * 1024;
      if (target.files[0].size > maxAllowedSize) {
      	// Here you can ask your users to load correct file
       	target.value = ''
      }
  }
})
<input type="file" id="input" />

파일 형식의 유효성검사 해야하는 경우 아래에 의견을 작성하면 솔루션을 공유하겠습니다.

(Spoiler: accept attribute is not bulletproof solution)


<script type="text/javascript">
    $(document).ready(function () {

        var uploadField = document.getElementById("file");

        uploadField.onchange = function () {
            if (this.files[0].size > 300000) {
                this.value = "";
                swal({
                    title: 'File is larger than 300 KB !!',
                    text: 'Please Select a file smaller than 300 KB',
                    type: 'error',
                    timer: 4000,
                    onOpen: () => {
                        swal.showLoading()
                        timerInterval = setInterval(() => {
                            swal.getContent().querySelector('strong')
                                .textContent = swal.getTimerLeft()
                        }, 100)
                    },
                    onClose: () => {
                        clearInterval(timerInterval)

                    }
                }).then((result) => {
                    if (
                        // Read more about handling dismissals
                        result.dismiss === swal.DismissReason.timer


                    ) {

                        console.log('I was closed by the timer')
                    }
                });

            };
        };



    });
</script>

Video file example (HTML + Javascript):

<form action="some_script" method="post" enctype="multipart/form-data">
<input id="max_id" type="hidden" name="MAX_FILE_SIZE" value="250000000" />
<input onchange="upload_check()" id="file_id" type="file" name="file_name" accept="video/*" />
<input type="submit" value="Upload"/>
</form>

<script>
function upload_check()
{
    var upl = document.getElementById("file_id");
    var max = document.getElementById("max_id").value;

    if(upl.files[0].size > max)
    {
       alert("File too big!");
       upl.value = "";
    }
};
</script>

ReferenceURL : https://stackoverflow.com/questions/5697605/limit-the-size-of-an-file-upload-html-input

반응형