program story

입력 유형 = 파일을 만드는 방법은 pdf 및 xls 만 허용해야합니다.

inputbox 2020. 11. 3. 07:59
반응형

입력 유형 = 파일을 만드는 방법은 pdf 및 xls 만 허용해야합니다.


나는 사용했다 <input type= "file" name="Upload" >

이제 .pdf 및 .xls 파일 만 허용하여이를 제한하고 싶습니다.

제출 버튼을 클릭하면이를 확인해야합니다.

웹 페이지에서 파일 (PDF / XLS)을 클릭하면 자동으로 열립니다.

누구든지 이것에 대한 몇 가지 예를 들어 주시겠습니까?


속성을 사용하고 accept허용 된 MIME 유형을 추가하여이를 수행 할 수 있습니다. 그러나 모든 브라우저가 해당 속성을 존중하는 것은 아니며 일부 코드 검사기를 통해 쉽게 제거 할 수 있습니다. 따라서 두 경우 모두 서버 측에서 파일 유형을 확인해야합니다 (두 번째 질문).

예:

<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />

세 번째 질문 "웹 페이지에서 파일 (PDF / XLS)을 클릭하면 자동으로 열립니다.":

당신은 그것을 달성 할 수 없습니다. 클라이언트 컴퓨터에서 PDF 또는 XLS를 여는 방법은 사용자가 설정합니다.


이것을 사용할 수 있습니다.

HTML

<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />

지원 만. PDF 및. XLS 파일


안타깝게도 선택시 보장 할 수있는 방법은 없습니다.

일부 브라우저 acceptinput태그 속성을 지원합니다 . 이것은 좋은 시작이지만 완전히 신뢰할 수는 없습니다.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

a를 사용하고 cfinput유효성 검사를 실행하여 제출시 파일 확장자 를 확인할 수 있지만 MIME 유형은 확인할 수 없습니다. 이것은 더 낫지 만 여전히 절대적인 것은 아닙니다. OSX의 파일에는 파일 확장자가없는 경우가 많거나 사용자가 파일 형식을 악의적으로 잘못 지정할 수 있습니다.

ColdFusion 에서는 결과 속성 ( )을 cffile사용하여 MIME 유형 을 확인할 수 있지만 업로드 후에 만 수행 할 수 있습니다. 이것이 최선의 방법이지만 MIME 유형이 여전히 잘못 될 수 있으므로 여전히 100 % 안전하지는 않습니다.contentTypecffile.contentType


셸을 포함한 모든 파일을 업로드 할 수있는 Firefox의 라이브 HTTP 헤더와 같은 도구가 있기 때문에 파일 서버 측을 필터링합니다. 사람들이 귀하의 사이트를 해킹 할 수 있습니다. 안전을 위해 서버 사이트를 수행하십시오.


JavaScript를 사용할 수 있습니다. JavaScript로이 작업을 수행하는 데있어 가장 큰 문제는 입력 파일을 재설정하는 것임을 고려하십시오. 음, 이것은 JPG로만 제한됩니다 (PDF의 경우 MIME 유형매직 넘버 를 변경해야합니다 ).

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.


While this particular example is for a multiple file upload, it gives the general information one needs:

https://developer.mozilla.org/en-US/docs/DOM/File.type

As far as acting upon a file upon /download/ this is not a Javascript question -- but rather a server configuration. If a user does not have something installed to open PDF or XLS files, their only choice will be to download them.


If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..

<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') : 
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>

You can then call the function from an event like the onClick of the above button, which looks like:

onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"

You can change this to: PDF and XLS

You can see it implemented over here: Demo

참고URL : https://stackoverflow.com/questions/12142536/how-to-make-input-type-file-should-accept-only-pdf-and-xls

반응형