2010-11-24 3 views
8

웹 응용 프로그램의 일반 텍스트 파일 용 가져 오기 스크립트를 설정하고 있습니다. 다음과 같이JavaScript의 FileReader 인터페이스를 사용할 때 파일의 내용 유형 감지

내 스크립트입니다 :

function dataImport(files) { 
    confirm("Are you sure you want to import the selected file? This will overwrite any data that is currently saved in the application workspace."); 
    for (i = 0; i < files.length; i++) { 
     file = files[i] 
     console.log(file) 
     var reader = new FileReader() 
     ret = [] 
     reader.onload = function(e) { 
      window.localStorage.setItem("ApplicationData", e.target.result); 
     } 
     reader.onerror = function(stuff) { 
      console.log("error", stuff) 
      console.log (stuff.getMessage()) 
     } 
     reader.readAsText(file) 
    } 
} 

본질적의 수정 this question에 제기합니다.

그러나 사용자는 기술적으로 모든 파일을 가져올 수 있습니다. 일반 텍스트 파일 용으로 설계 되었기 때문에 다른 유형의 파일을 가져 오는 경우 문제가 발생할 수 있습니다.

브라우저에서 가져올 파일의 콘텐츠 유형을 감지했습니다. 여기에 예제가 있습니다.

fileName: "ideas.txt" 
fileSize: 377 
name: "ideas.txt" 
size: 377 
type: "text/plain" 
webkitRelativePath: "" 

이 가능하고, 스크립트 파일의 내용 유형을 감지 인수를 설정하고 지정된 적합한 컨텐츠 유형의 숫자 ​​중 하나가 아닌 경우 스크립트를 가지고 있나요 가져 오기를 거부합니까?

미리 조언 해 주셔서 감사합니다.

+0

내가 생각하는 '콘텐츠 유형을 감지'하여가 u는 파일의 확장자에서 추론, 의미 .. 확장하여 –

+0

추론은 그것을 할 수있는 하나 개의 방법이 될 것입니다,하지만 난 내가 할 수있는 것을 기대했다 이마에 무엇이든지 접근하라. 예를 들어 "text/plain"또는 "text/x-tex"또는 "image/jpeg"등의 파일이 있습니다. –

답변

14
if (file.type.match('text/plain')) { 
    // file type is text/plain 
} else { 
    // file type is not text/plain 
} 

경우 String.match는 정규식, 그래서 당신이 파일이 텍스트의 어떤 유형이 있는지 확인하고 싶을 경우, 당신은 그렇게 할 수 있습니다 : 콘텐츠 유형을 읽을 수 있습니다

if (file.type.match('text.*')) { 
    // file type starts with text 
} else { 
    // file type does not start with text 
} 
10

다음 코드를

// Note: File is a file object than can be read by the HTML5 FileReader API 
var reader = new FileReader(); 

reader.onload = function(event) { 
    var dataURL = event.target.result; 
    var mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0]; 
    alert(mimeType); 
}; 

reader.readAsDataURL(file); 
+0

다른 옵션 (더 간단)은 dataURL.split (",") [0] .split (":") [1] .split (";") [0] .indexOf ([your mime type] > = 0 – Alberto