Javascript 에서 파일을 읽어들여야 하는 경우가 생겼습니다. 뭐... html5 에 FileReader라는게 생겼죠.. image를 예제로 해서 이미지를 읽어들이고 예제로 보여주고 나서 바로 업로드가 가능하도록 구현하였습니다.
function readFile() {
var file = document.getElementById("file").files[0];
document.getElementById("fileName").textContent = file.name;
document.getElementById("fileSize").textContent = "(" + file.size + "byte)";
var reader = new FileReader();
reader.onload = function() {
var display = document.getElementById("content");
var img = document.getElementById("test");
img.src = "data:image/jpeg;base64,"+encode64(reader.result);
display.textContent = encode64(reader.result);
base64_datas = encode64(reader.result);
};
reader.onerror = function(evt) {
alert(evt.target.error.code);
};
var encodingList = document.getElementById("encoding");
var encoding = encodingList.options[encodingList.selectedIndex].value;
reader.readAsBinaryString(file, encoding);
};
[소스1.] 파일을 읽어들이는 소스
function upload() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleFileData;
xhr.open("POST","upload.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//요청헤더의 정의
//alert(base64_datas);
xhr.send("img_datas="+base64_datas);
}
function handleFileData() {
// only if req shows "loaded"
if (xhr.readyState == 4) {
// only if "OK"
if (xhr.status == 200) {
console.log(xhr.responseText);
alert('Upload complete!');
} else {
alert("There was a problem retrieving the XML data:\n" +
xhr.statusText);
}
}
}
[소스2.] php로 업로드하는 소스.파일을 주고 받으려면 base64로 바꿔야겠죠..
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
} while (i < input.length);
return output;
}
function decode64(input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
} while (i < input.length);
return output;
}
function encode64Han(str) {
return encode64(escape(str))
}
function decode64Han(str) {
return unescape(decode64(str))
}
이렇게 해서 파일 읽어서 보내면...PHP에서는..
$input = file_get_contents("php://input");
$ex = explode("img_datas=", $input);
$ex = explode("&", $ex[1]);
$fh2 = fopen("./upload/test.jpg", 'w') or die("can't open file");
fwrite($fh2, base64_decode($ex[0]));
fclose($fh2);
?>
이렇게 받으시면 되요..여기서 중요한건.. file_get_contents 인데.. 저렇게 안하고 $_POST['img_datas']로 하시면 데이터가 중간에 손실되요ㅠㅠ
그거때문에 몇시간을 고생해서...ㅠㅠㅠ흑흑..
'프로그래밍!! > Javascript' 카테고리의 다른 글
| Binary File 읽어서 base64로 인코딩 후 php로 보내기 (0) | 2011/12/06 |
|---|
web.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
// return super.shouldOverrideUrlLoading(view, url);
view.loadUrl(url);
return true; // TRUE이면 내부처리, FALSE이면 내장 브라우저에서
}
});
web.loadUrl("주소");
보통 웹뷰를 쓸때 어플 내부에 웹을 띄우기 위해서인데, 내부 처리하는 경우가 더 많다고 생각한다.
그러므로..
'프로그래밍!! > Android' 카테고리의 다른 글
| WebView에서 url이 로딩될 때 내부처리/외부처리 바꾸기 (0) | 2011/09/02 |
|---|---|
| 안드로이드에서 웹으로 데이터 넘기기. (0) | 2011/08/08 |
| 안드로이드에서 버전업 했을때 버전 확인하고 다운 받기 (0) | 2011/07/26 |
| 안드로이드에서 SharedPreferences(임시 저장 공간) 활용하기 (0) | 2011/07/26 |
| Android에서 자기 번호 가져오기 (0) | 2011/07/26 |
Python 2.7 을 설치( http://www.python.org/download/ )하고 그 버전에 맞는 py2exe 를 받자..(전 2.7버전 다운로드 했어ㅛ)
http://sourceforge.net/projects/py2exe/files/py2exe/
설치파일을 만들 test.py
from distutils.core import setup
import py2exesetup(console=['Target.py'])
test.py 를 이런 내용으로 만들고 Target.py(py -> exe를 할 파일)가 있는곳에 넣는다.
cmd 입력창에서
C:\Python27\python.exe test.py py2exe
이렇게 하면 dist 폴더에 exe 파일이 생성된다!!
http://sourceforge.net/projects/py2exe/files/py2exe/
설치파일을 만들 test.py
from distutils.core import setup
import py2exesetup(console=['Target.py'])
test.py 를 이런 내용으로 만들고 Target.py(py -> exe를 할 파일)가 있는곳에 넣는다.
cmd 입력창에서
C:\Python27\python.exe test.py py2exe
이렇게 하면 dist 폴더에 exe 파일이 생성된다!!
'프로그래밍!! > 기타' 카테고리의 다른 글
| PY2EXE. py에서 실행파일(exe)로 만드는 방법 (0) | 2011/08/16 |
|---|---|
| Putty Portable 6.0 (0) | 2011/08/08 |
| Balsamiq : 빠른 UI 디자인을 위한 도구 (0) | 2011/03/18 |
| UVA PROBLEM RANKING BY INCREASING DIFFICULTY (0) | 2011/02/23 |
| Doxygen 기본ㅋ (0) | 2011/02/23 |






Recent Comment