programing

폰갭을 사용하여 전화번호부에 파일이 있는지 확인하는 방법

sourcejob 2023. 9. 1. 20:51
반응형

폰갭을 사용하여 전화번호부에 파일이 있는지 확인하는 방법

폰갭 1.4.1과 센차로 pdf파일을 다운받아 읽는 안드로이드 앱을 작성하고 있습니다.폰갭 메소드, 자바스크립트 또는 아약스 중 하나를 사용하여 전화번호부에 파일이 있는지 확인하려면 어떻게 해야 합니까?

저도 같은 문제가 있었습니다.저는 일을 하기 위해 Darkaiico의 대답을 얻을 수 없었지만 Kurt의 대답으로 그것을 할 수 있었습니다.

내 코드는 다음과 같습니다.

function checkIfFileExists(path){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
        fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
    }, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
    alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
    alert("file does not exist");
}
function getFSFail(evt) {
    console.log(evt.target.error.code);
}

그런 다음 다음과 같이 실행하면 됩니다.

checkIfFileExists("path/to/my/file.txt");

나는 파일에 대한 핸들을 사용하여 얻습니다..getFile('fileName',{create:false},success,failure)방법.만약 내가 받는다면,success파일이 있는 경우 콜백합니다. 그렇지 않으면 파일에 문제가 있음을 의미합니다.

위의 답변은 저에게 효과가 없었지만, 이것은 효과가 있었습니다.

window.resolveLocalFileSystemURL(fullFilePath, success, fail);

출처: http://www.raymondcamden.com/2014/07/01/Cordova-Sample-Check-for-a-file-and-download-if-it-isnt-there

폰갭에서 FileReader 개체를 사용하여 파일이 존재하는지 확인할 수 있습니다.다음을 확인할 수 있습니다.

var reader = new FileReader();
var fileSource = <here is your file path>

reader.onloadend = function(evt) {

    if(evt.target.result == null) {
       // If you receive a null value the file doesn't exists
    } else {
        // Otherwise the file exists
    }         
};

// We are going to check if the file exists
reader.readAsDataURL(fileSource);   

다케이코, 커트 그리고 토마스의 대답은 저에게 효과가 없었습니다.제게 효과가 있었던 것은 이렇습니다.

$.ajax({
url:'file///sdcard/myfile.txt',
type:'HEAD',
error: function()
{
    //file not exists
alert('file does not exist');
},
success: function()
{
    //file exists
alert('the file is here');
}
});

@PassKit이 맞습니다. 저의 경우 이벤트 수신기를 추가해야 했습니다.

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
       window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError);
}

그런 다음 "fsSuccess" 함수의 "fileSystemRoot" 값에 대해

var fileSystemRoot; // Global variable to hold filesystem root

function fsSuccess(fileSystem) {
       fileSystemRoot = fileSystem.root.toURL();
}

"checkFileExists" 함수

function checkFileExists(fileName) {
    var http = new XMLHttpRequest();
    http.open('HEAD', fileName, false);
    http.send(null);
    if (http.status.toString() == "200") {
        return true;
    }
    return false
}

파일이 존재하는지 확인하기 위해

if (checkFileExists(fileSystemRoot + "fileName")) {
     // File Exists
} else {
     // File Does Not Exist
}

IOS의 var fileSystemRoot가 "cdvfile://localhost/persistent/"를 반환하고 파일이 "//var/mobile/Containers/Data/Application/{App"에 저장되었습니다.ID}/문서"

@PassKit 덕분에 동기식 모드로 실행되고 IOS 8.1에서 테스트되었습니다.

커트와 토마스는 더 나은 답변을 해줬는데, 다케이코의 기능은 파일이 존재하는지 확인할 뿐만 아니라 파일을 열어 끝까지 읽어주기 때문입니다.

이것은 작은 파일의 문제가 아니지만, 큰 파일을 확인하면 앱이 충돌할 수 있습니다.

어쨌든 .getFile 메서드를 사용하십시오. 이것이 가장 좋은 옵션입니다.

다음 코드 스니펫을 테스트했으며 PhoneGap 3.1에서 잘 작동합니다.

String.prototype.fileExists = function() {
filename = this.trim();

var response = jQuery.ajax({
    url: filename,
    type: 'HEAD',
    async: false
}).status;  

return (response != "200") ? false : true;}

if (yourFileFullPath.fileExists())
{}

모든 현재 답변의 문제는 글로벌 변수를 업데이트하는 비동기 콜백에 의존한다는 것입니다.여러 파일을 확인하는 경우 변수가 다른 콜백에 의해 설정될 위험이 있습니다.

기본적인 Javascript XMLHttpRequest 검사는 Javascript를 통해 파일에 액세스할 수 있는지 동시에 확인하는 데 적합합니다.

function checkFileExists(fileName){

    var http = new XMLHttpRequest();
    http.open('HEAD', fileName, false);
    http.send(null);
    return (http.status != 404);
}

파일의 전체 경로를 전달하기만 하면 다음을 안정적으로 사용할 수 있습니다.

if (checkFileExists(fullPathToFile)) {
    // File Exists
} else {
    // File Does Not Exist
}

루트 경로를 변수에 저장하려면 다음을 사용합니다.

var fileSystemRoot; // Global variable to hold filesystem root

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError);

function fsError() {
    console.log("Failed to get Filesystem");
}

function fsSuccess(fileSystem) {
    console.log("Got Filesystem: Root path " + fileSystem.root);

    // save the file to global variable for later access
    window.fileSystemRoot = fileSystem.root;
}   

참고:

파일 시스템을 가져올 때 매크로 pg 개체 아래의 변수에 저장합니다.

pg = {fs:{}}    // I have a "GOTFS" function... a "fail" function
pg.fs.filesystem = window.requestFileSystem(window.PERSISTENT, 0, pg.fs.GOTFS, pg.fs.fail);

그래서 내 코드는 꽤 간단합니다...

var fileExists = function(path, existsCallback, dontExistsCallback){
    pg.fs.fileSystem.root.getFile(path, { create: false }, existsCallback, dontExistsCallback);
        // "existsCallback" will get fileEntry as first param
    }

이 코드는 사용자 지정 사례에 사용할 수 있습니다. 전체 설명서는 여기에 있습니다. 없는 경우 다운로드하십시오.

document.addEventListener("deviceready", init, false);

//The directory to store data
var store;

//Used for status updates
var $status;

//URL of our asset
var assetURL = "https://raw.githubusercontent.com/cfjedimaster/Cordova-Examples/master/readme.md";

//File name of our important data file we didn't ship with the app
var fileName = "mydatafile.txt";

function init() {

$status = document.querySelector("#status");

$status.innerHTML = "Checking for data file.";

store = cordova.file.dataDirectory;

//Check for the file.
window.resolveLocalFileSystemURL(store + fileName, appStart, downloadAsset);

}

function downloadAsset() {
var fileTransfer = new FileTransfer();
console.log("About to start transfer");
fileTransfer.download(assetURL, store + fileName,
function(entry) {
console.log("Success!");
appStart();
},
function(err) {
console.log("Error");
console.dir(err);
});
}

//I'm only called when the file exists or has been downloaded.
function appStart() {
$status.innerHTML = "App ready!";
}
    var fileexist;
function checkIfFileExists(path){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
        fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
    }, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
    alert("File " + fileEntry.fullPath + " exists!");
    fileexist = true;
}
function fileDoesNotExist(){
    alert("file does not exist");
   fileexist = false;
}
function getFSFail(evt) {
    console.log(evt.target.error.code);
    fileexist=false;
}

이제 조건을 사용할 수 있습니다.

if(fileexist=="true"){
//do something;
}
else if(fileexist=="false"){
//do something else
}

부울 호환 방법이 필요한 경우...

function checkIfFileExists(path){
    var result = false;

    window.requestFileSystem(
        LocalFileSystem.PERSISTENT, 
        0, 
        function(fileSystem){
            fileSystem.root.getFile(
                path, 
                { create: false }, 
                function(){ result = true; }, // file exists
                function(){ result = false; } // file does not exist
            );
        },
        getFSFail
    ); //of requestFileSystem

    return result;
}

위의 @Thomas Soti 답변을 사용하여 간단한 예/아니오 답변으로 정리했습니다.

function fileExists(fileName) {
  window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
      fileSystem.root.getFile(cordova.file.dataDirectory + fileName, { create: false }, function(){return true}, function(){return false});
  }, function(){return false}); //of requestFileSystem
}
// called as
if (fileExists("blah.json")) {
or
var fe = fileExists("blah.json) ;

수정...작동하지 않습니다.저는 지금 수정 작업 중입니다.

언급URL : https://stackoverflow.com/questions/10294166/how-to-check-a-files-existence-in-phone-directory-with-phonegap

반응형