다양한 브라우저에서 javascript로 클라이언트 측 파일 내용 읽기
브라우저를 통해 클라이언트 컴퓨터의 파일 내용을 읽을 수있는 스크립트 전용 솔루션을 제공하려고합니다.
Firefox 및 Internet Explorer에서 작동하는 솔루션이 있습니다. 예쁘지는 않지만 지금은 시도하고 있습니다.
function getFileContents() {
var fileForUpload = document.forms[0].fileForUpload;
var fileName = fileForUpload.value;
if (fileForUpload.files) {
var fileContents = fileForUpload.files.item(0).getAsBinary();
document.forms[0].fileContents.innerHTML = fileContents;
} else {
// try the IE method
var fileContents = ieReadFile(fileName);
document.forms[0].fileContents.innerHTML = fileContents;
}
}
function ieReadFile(filename)
{
try
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
}
catch (Exception)
{
return "Cannot open file :(";
}
}
전화를 걸어 getFileContents()
내용을 fileContents
텍스트 영역에 씁니다 .
다른 브라우저에서이 작업을 수행하는 방법이 있습니까?
나는 현재 Safari와 Chrome에 가장 관심이 많지만 다른 브라우저에 대한 제안에 열려 있습니다.
편집 : "왜 이렇게 하시겠습니까?"라는 질문에 대한 응답 :
기본적으로 클라이언트 측에서 일회성 암호와 함께 파일 내용을 해시하여이 정보를 확인으로 다시 보낼 수 있습니다.
Edited to add information about the File API
Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader
API described here, though not yet the File
API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:
var file = document.getElementById("fileForUpload").files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
document.getElementById("fileContents").innerHTML = evt.target.result;
}
reader.onerror = function (evt) {
document.getElementById("fileContents").innerHTML = "error reading file";
}
}
Original answer
There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName
and fileSize
. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.
If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.
In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file">
tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.
function onFileLoad(elementId, event) {
document.getElementById(elementId).innerText = event.target.result;
}
function onChooseFile(event, onLoadFileHandler) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
let input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
let file = input.files[0];
let fr = new FileReader();
fr.onload = onLoadFileHandler;
fr.readAsText(file);
}
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />
<p id="contents"></p>
Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX
var CallBackFunction = function(content)
{
alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction)
{
try
{
var file = FileElement.files[0];
var contents_ = "";
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(evt)
{
CallBackFunction(evt.target.result);
}
reader.onerror = function (evt) {
alert("Error reading file");
}
}
}
catch (Exception)
{
var fall_back = ieReadFile(FileElement.value);
if(fall_back != false)
{
CallBackFunction(fall_back);
}
}
}
///Reading files with Internet Explorer
function ieReadFile(filename)
{
try
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
}
catch (Exception)
{
alert(Exception);
return false;
}
}
'Programing' 카테고리의 다른 글
여러 항목에 의한 mysql 쿼리 순서 (0) | 2020.09.08 |
---|---|
'std :;' (0) | 2020.09.08 |
IE CSS 필터를 재설정하거나 무시하려면 어떻게합니까? (0) | 2020.09.08 |
jquery가있는 jsonp (0) | 2020.09.08 |
이 동사 유형으로 콘텐츠 본문을 보낼 수 없습니다. (0) | 2020.09.08 |