2011-07-27 9 views
28

아약스를 사용하여 dataURL을 보내려면 javascript의 file 객체로 dataURL을 변환해야합니다. 가능한가? 그렇다면, 어떻게 말해주십시오. 감사.dataURL을 javascript의 파일 객체로 변환하는 방법은 무엇입니까?

업데이트 :
모든 답변을 주셔서 감사합니다. 그러나 이것은 매우 오래된 질문이며, 지금까지 충분한 답변을 수집했다고 생각합니다.

+0

더 알려주세요. – cwallenpoole

+0

cwallenpoole, 그것의 큰 코드, 이미지가 몸에 붙어 있기 때문에 모든 것이 잘 작동하기 전에 필요한 것을 말해주세요. 여기에 게시 해 드리겠습니다. – kapv89

+0

스크립트/페이지에'formData' 란 무엇입니까? –

답변

38

ajax를 통해 보낼 필요가있는 경우 File 개체를 사용할 필요가 없으므로 BlobFormData 개체 만 필요합니다.

내가 sidenote로, 왜 그냥 아약스를 통해 서버에 base64 문자열을 보내고 PHP의 base64_decode을 사용하여 바이너리 서버 측으로 변환하지 않습니까? 어쨌든, this answer 크롬 (13)의 작품과 웹킷 나이틀리의 표준 호환 코드 :

function dataURItoBlob(dataURI) { 
    // convert base64 to raw binary data held in a string 
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this 
    var byteString = atob(dataURI.split(',')[1]); 

    // separate out the mime component 
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 

    // write the bytes of the string to an ArrayBuffer 
    var ab = new ArrayBuffer(byteString.length); 
    var ia = new Uint8Array(ab); 
    for (var i = 0; i < byteString.length; i++) { 
     ia[i] = byteString.charCodeAt(i); 
    } 

    //Old Code 
    //write the ArrayBuffer to a blob, and you're done 
    //var bb = new BlobBuilder(); 
    //bb.append(ab); 
    //return bb.getBlob(mimeString); 

    //New Code 
    return new Blob([ab], {type: mimeString}); 


} 

은 그럼 그냥 새로운 FormData 객체에 방울을 추가하고 아약스 사용하여 서버에 게시 :

var blob = dataURItoBlob(someDataUrl); 
var fd = new FormData(document.forms[0]); 
var xhr = new XMLHttpRequest(); 

fd.append("myFile", blob); 
xhr.open('POST', '/', true); 
xhr.send(fd); 
+1

답변 해 주셔서 감사합니다. 그것의 캔버스 기반 이미지 resizer, 워터 마크 및 업 로더. 프로젝트가 사용되기를 기다리는 중 – kapv89

+0

Firefox에서는 양식이 없으면 FormData를 다음과 같이 작성해야합니다. 'new FormData(); 그렇지 않으면 예외가 발생합니다. –

+0

왜 여기에'callback' 인자가 있나요? 그것을 제거해야 할 것 같습니다. –

29

BlobBuilder은 더 이상 사용되지 않아야합니다. 이전 BlobBuilder 대신 Blob을 사용하십시오. 코드는 매우 간단하고 간단합니다.

File 객체는 Blob 객체에서 상속됩니다. FormData 객체와 함께 둘 다 사용할 수 있습니다.

function dataURLtoBlob(dataurl) { 
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], 
     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 
    while(n--){ 
     u8arr[n] = bstr.charCodeAt(n); 
    } 
    return new Blob([u8arr], {type:mime}); 
} 

사용 dataURLtoBlob() 함수는 블롭 및 서버에 아약스를 보내 dataURL을 변환합니다.

var dataurl = 'data:text/plain;base64,aGVsbG8gd29ybGQ='; 
var blob = dataURLtoBlob(dataurl); 
var fd = new FormData(); 
fd.append("file", blob, "hello.txt"); 
var xhr = new XMLHttpRequest(); 
xhr.open('POST', '/server.php', true); 
xhr.onload = function(){ 
    alert('upload complete'); 
}; 
xhr.send(fd); 

또 다른 방법 :

당신은 또한 파일 객체가,이 이름/FileName 속성입니다있다 (파일 객체에 URL을 변환 fetch을 사용할 수 있습니다 예를 들어

BLOB 객체와 다름)

코드가 매우 짧고 사용하기 쉽습니다. (works in Chrome and Firefox)

//load src and convert to a File instance object 
//work for any type of src, not only image src. 
//return a promise that resolves with a File instance 

function srcToFile(src, fileName, mimeType){ 
    return (fetch(src) 
     .then(function(res){return res.arrayBuffer();}) 
     .then(function(buf){return new File([buf], fileName, {type:mimeType});}) 
    ); 
} 

사용 예 1 : 그냥 객체를 파일로 변환

srcToFile(
    'data:text/plain;base64,aGVsbG8gd29ybGQ=', 
    'hello.txt', 
    'text/plain' 
) 
.then(function(file){ 
    console.log(file); 
}) 

사용 예 2 : 객체를 제출하고 나는이에 도착 몇 가지 조사 후 서버

srcToFile(
    'data:text/plain;base64,aGVsbG8gd29ybGQ=', 
    'hello.txt', 
    'text/plain' 
) 
.then(function(file){ 
    console.log(file); 
    var fd = new FormData(); 
    fd.append("file", file); 
    return fetch('/server.php', {method:'POST', body:fd}); 
}) 
.then(function(res){ 
    return res.text(); 
}) 
.then(console.log) 
.catch(console.error) 
; 
+2

깔끔하고 깨끗한 답변으로 정말 즐거웠지만 다른 답변에서는 ArrayBuffer의 사용법을 알 수 있습니다. ArrayBuffer와 왜 여기에 사용되지 않는지 사용법을 설명해 주시겠습니까? – Ali

+0

좋아했습니다! 가장 좋은 대답은 imo –

1

에 업로드 변환 하나 :

function dataURItoBlob(dataURI) { 
 
    // convert base64 to raw binary data held in a string 
 
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this 
 
    var byteString = atob(dataURI.split(',')[1]); 
 
    // separate out the mime component 
 
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 
 
    // write the bytes of the string to an ArrayBuffer 
 
    var ab = new ArrayBuffer(byteString.length); 
 
    var dw = new DataView(ab); 
 
    for(var i = 0; i < byteString.length; i++) { 
 
     dw.setUint8(i, byteString.charCodeAt(i)); 
 
    } 
 
    // write the ArrayBuffer to a blob, and you're done 
 
    return new Blob([ab], {type: mimeString}); 
 
} 
 

 
module.exports = dataURItoBlob;

관련 문제