2013-12-17 2 views
0

양식의 파일 입력에서 이미지를 가져와 localstorage에 넣을 수있는 함수를 작성 중입니다. I 쓴 함수는이를 달성하기 localstorage 함수의 이미지가 작동하지 않습니다.

function getImage() { 
    var pic = document.getElementById("image").files[0]; 
    var imgUrl; 
    var reader = new FileReader(); 
    reader.onload = function(e) { 
     var imgURL = reader.result; 
     saveDataToLocalStorage(imgURL); 
     return imgUrl; 
    } 
} 

그럼 다른 함수 I이 함수를 호출 나 이미지를 포함하는 다른 형태의 입력의 값을 저장하는 JSON 엔트리를 생성한다. 그것은 다음과 같습니다 슬프게도 imgUrl의 값이 정의되지
var imgUrl = getImage(); 

    // Create new JSON entry 
    var json_entry = {'title': titleField.val(), 
         'image': imgUrl, 
         'content': contentField.val(), 
         'location': location}; 

.. 어떤 콘솔 오류가 없습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 어떻게 해결할 수 있습니까?

+1

이진 데이터를 지원하지 않는 localStorage에 이진 데이터를 저장하려고하는 것처럼 보입니까? – adeneo

+0

문제를 해결하는 방법을 알고 계십니까? – aardnoot

+0

나는 그것을 고치는 법을 모른다. 위의 코드는 다음 예제를 기반으로합니다. http://jsfiddle.net/VXdkC/2/ – aardnoot

답변

1

나는 정직하게 FileReader 객체에 대해 잘 모르겠지만, 난 그냥 (적어도) 한 가지가 꺼져 있는지 당신의 JS에서이기는에서 볼 수

var imgUrl = getImage(); 

귀하의 getImage 기능은 반환하지 않습니다 아무것도; 그래서 imgUrl은 분명히 위에 undefined이 될 것입니다.

function getImage(callback) { 
    // What are you doing with this? 
    var pic = document.getElementById("image").files[0]; 

    var reader = new FileReader(); 
    reader.onload = function(e) { 
     var imgURL = reader.result; 
     saveDataToLocalStorage(imgURL); 

     // Note the difference here: rather than return from the event handler 
     // (which effectively does nothing) we pass the result to a callback. 
     callback(imgUrl); 
    } 

    // I assume you actually need to load something with the FileReader? 
} 

: 그리고 당신은 당신의 FileReaderresult 속성 무언가를하려면

는, 당신은 당신이 (비동기)를 취급하고 있기 때문에 onload 이벤트 콜백/그렇게 w 수행해야합니다

getImage(function(imgUrl) { 
    var json_entry = { 
     'title': titleField.val(), 
     'image': imgUrl, 
     'content': contentField.val(), 
     'location': location 
    }; 
}); 
0

독자를 readAsDataUrl으로 설정하는 것을 잊어 버린 것 같습니다. 아마도 localStorage은 이진 데이터를 직렬화하는 방법을 본질적으로 알고 있지 않기 때문에이 값은 undefined으로 다시 올 것입니다. 리더를 readAsDataUrl으로 설정하면 reader.result로드가 변경됩니다.

var reader = new FileReader(); 
reader.onload = function(e) { 
    var imgURL = reader.result; 
    saveDataToLocalStorage(imgURL); 
    callback(imgUrl); 
}; 
// add this line 
reader.readAsDataURL(pic); 

this 기사를 살펴, 파일 읽기 제목 특히 섹션이 있습니다. 링크 된 예제에서 저자는 reader.result 대신 e.target.result을 사용합니다. 이 이어야합니다.

관련 문제