programing

데이터 변환 방법javascript로 파일 개체에 URL을 지정하시겠습니까?

lastcode 2023. 10. 24. 21:21
반응형

데이터 변환 방법javascript로 파일 개체에 URL을 지정하시겠습니까?

데이터를 변환해야 합니다.AJAX를 사용하여 파일을 전송하기 위해 자바스크립트로 파일 개체에 URL을 지정합니다.가능합니까?만약 그렇다면 방법을 알려주시기 바랍니다.

ajax를 통해 보내야 한다면 ajax를 사용할 필요가 없습니다.File개체,만Blob그리고.FormData물건이 필요합니다.

참고로, 그냥 base64 문자열을 ajax를 통해 서버로 보내고 PHP의 것을 사용하여 바이너리 서버 쪽으로 변환하는 것이 어떻습니까?base64_decode예를 들면요?어쨌든 이 답변의 표준 호환 코드는 Chrome 13과 WebKit nightly에서 작동합니다.

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});


}

그런 다음 blob을 새 FormData 개체에 추가하고 ajax를 사용하여 서버에 게시합니다.

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);

BlobBuilder는 더 이상 사용되지 않으므로 더 이상 사용하지 마십시오.기존 블롭빌더 대신 블롭을 사용합니다.코드는 매우 깨끗하고 간단합니다.

파일 개체가 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});
}

데이터를 사용합니다.데이터 변환을 위한 URL to Blob() 함수ajax를 차단하고 서버로 전송하기 위한 URL입니다.

예를 들어 다음과 같습니다.

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);

다른 방법:

fetch를 사용하여 URL을 파일 개체로 변환할 수도 있습니다(파일 개체에는 name/fileName 속성이 있으며 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)
;

데이터에서 블랍을 생성하는 방법URL:

const response = await fetch(dataURL);
const blob = await response.blob(); 

blob에서 파일을 만드는 방법:

const file = new File(
  [blob],
  "fileName.jpg",
  {
    type: "image/jpeg",
    lastModified: new Date()
  }
);

데이터를 변환하려면URL을 입력합니다.File물건.

데이터를 변환해야 합니다.URL을 입력합니다.Blob그 다음에 변환합니다.Blob안으로File. 그 기능은 매튜의 답변에서 나온 것입니다.(https://stackoverflow.com/a/7261048/13647044)

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);
      }
      return new Blob([ab], { type: mimeString });
    }

const blob = dataURItoBlob(url);
const resultFile = new File([blob], "file_name");

그 외에, 당신은 웹사이트에서 옵션을 가질 수 있습니다.File개체가 초기화되었습니다.파일() 생성자에 대한 참조입니다.

const resultFile = new File([blob], "file_name",{type:file.type,lastModified:1597081051454});

유형은 다음과 같습니다.[MIME][1]활자를 치다image/jpeg) 및 예제에서 마지막으로 수정한 값은 다음과 같습니다.Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time)

최신 브라우저:

const dataURLtoBlob = (dataURL) => {
        fetch(dataURL)
            .then(res => res.blob())
            .then(blob => console.log(blob))
            .catch(err => console.log(err))
    }

몇 가지 조사 끝에 저는 이 문제에 도달했습니다.

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;

언급URL : https://stackoverflow.com/questions/6850276/how-to-convert-dataurl-to-file-object-in-javascript

반응형