복붙노트

[JQUERY] 어떻게 방울을 업로드 자바 스크립트를 할 수 있습니까?

JQUERY

어떻게 방울을 업로드 자바 스크립트를 할 수 있습니까?

해결법


  1. 1.이 시도

    이 시도

    var fd = new FormData();
    fd.append('fname', 'test.wav');
    fd.append('data', soundBlob);
    $.ajax({
        type: 'POST',
        url: '/upload.php',
        data: fd,
        processData: false,
        contentType: false
    }).done(function(data) {
           console.log(data);
    });
    

    당신은 FormData API를 사용하고 false로 jQuery.ajax의 processData과의 contentType을 설정해야합니다.


  2. 2.당신은 실제로 자바 스크립트에서 서버로의 Blob을 보낼 FormData를 사용할 필요가 없습니다 (그리고 파일도의 Blob)입니다.

    당신은 실제로 자바 스크립트에서 서버로의 Blob을 보낼 FormData를 사용할 필요가 없습니다 (그리고 파일도의 Blob)입니다.

    jQuery를 예 :

    var file = $('#fileInput').get(0).files.item(0); // instance of File
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: file,
      contentType: 'application/my-binary-type', // set accordingly
      processData: false
    });
    

    바닐라 자바 ​​스크립트 예제 :

    var file = $('#fileInput').get(0).files.item(0); // instance of File
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload.php', true);
    xhr.onload = function(e) { ... };
    xhr.send(file);
    

    당신이 (즉, 백 엔드는 다중 양식 데이터를 소비)는 "AJAX"구현과 기존의 HTML의 다중 양식을 교체 할 경우 부여, 당신은 다른 답변에 설명 된대로 FormData 객체를 사용하려고합니다.

    출처 : XMLHttpRequest2의 새로운 트릭 | HTML5 바위


  3. 3.나는 모양 작업은 위의 예를 가져올 수 없습니다 나는 정확히 upload.php로에 무엇인지 알고 싶었다. 그래서 여기 당신은 간다 :

    나는 모양 작업은 위의 예를 가져올 수 없습니다 나는 정확히 upload.php로에 무엇인지 알고 싶었다. 그래서 여기 당신은 간다 :

    (크롬 28.0.1500.95 만 테스트)

    // javascript function that uploads a blob to upload.php
    function uploadBlob(){
        // create a blob here for testing
        var blob = new Blob(["i am a blob"]);
        //var blob = yourAudioBlobCapturedFromWebAudioAPI;// for example   
        var reader = new FileReader();
        // this function is triggered once a call to readAsDataURL returns
        reader.onload = function(event){
            var fd = new FormData();
            fd.append('fname', 'test.txt');
            fd.append('data', event.target.result);
            $.ajax({
                type: 'POST',
                url: 'upload.php',
                data: fd,
                processData: false,
                contentType: false
            }).done(function(data) {
                // print the output from the upload.php script
                console.log(data);
            });
        };      
        // trigger the read from the reader...
        reader.readAsDataURL(blob);
    
    }
    

    먼저 upload.php의 내용 :

    <?
    // pull the raw binary data from the POST array
    $data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
    // decode it
    $decodedData = base64_decode($data);
    // print out the raw data, 
    echo ($decodedData);
    $filename = "test.txt";
    // write the data out to the file
    $fp = fopen($filename, 'wb');
    fwrite($fp, $decodedData);
    fclose($fp);
    ?>
    

  4. 4.나는 FormData를 사용하지만, BLOB를 전송하는 자바 스크립트 객체를 사용하지 않음으로써 작업에 @yeeking 예를 얻을 수 있었다. 사운드 덩어리와 작품 recorder.js를 사용하여 만들었습니다. 크롬 버전 32.0.1700.107에서 테스트

    나는 FormData를 사용하지만, BLOB를 전송하는 자바 스크립트 객체를 사용하지 않음으로써 작업에 @yeeking 예를 얻을 수 있었다. 사운드 덩어리와 작품 recorder.js를 사용하여 만들었습니다. 크롬 버전 32.0.1700.107에서 테스트

    function uploadAudio( blob ) {
      var reader = new FileReader();
      reader.onload = function(event){
        var fd = {};
        fd["fname"] = "test.wav";
        fd["data"] = event.target.result;
        $.ajax({
          type: 'POST',
          url: 'upload.php',
          data: fd,
          dataType: 'text'
        }).done(function(data) {
            console.log(data);
        });
      };
      reader.readAsDataURL(blob);
    }
    

    먼저 upload.php의 내용

    <?
    // pull the raw binary data from the POST array
    $data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
    // decode it
    $decodedData = base64_decode($data);
    // print out the raw data,
    $filename = $_POST['fname'];
    echo $filename;
    // write the data out to the file
    $fp = fopen($filename, 'wb');
    fwrite($fp, $decodedData);
    fclose($fp);
    ?>
    

  5. 5.이 최신과 답변이 API를 가져 오기 업데이트하고 jQuery를 필요로하지 않는다.

    이 최신과 답변이 API를 가져 오기 업데이트하고 jQuery를 필요로하지 않는다.

    면책 조항 : IE, 오페라 미니와 이전 버전의 브라우저에서 작동하지 않습니다. caniuse를 참조하십시오.

    기본 가져 오기

    그것은 단순하게 할 수있다 :

      fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                    .then(response => console.log(response.text()))
    

    오류 처리로 가져 오기

    오류 처리를 추가 한 후, 그것은 같이 수 :

    fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => {
                    if (response.ok) return response;
                    else throw Error(`Server returned ${response.status}: ${response.statusText}`)
                })
                .then(response => console.log(response.text()))
                .catch(err => {
                    alert(err);
                });
    

    PHP 코드

    이 upload.php로의 서버 측 코드입니다.

    <?php    
        // gets entire POST body
        $data = file_get_contents('php://input');
        // write the data out to the file
        $fp = fopen("path/to/file", "wb");
    
        fwrite($fp, $data);
        fclose($fp);
    ?>
    

  6. 6.나는 모든 솔루션 위뿐만 아니라 관련 답변에 그뿐만 아니라 시도. 솔루션 모두에게 readAs를 호출을 포함하지만 HTMLInputElement의 파일 속성에 수동으로 BLOB 전달에 국한되지 * 얻어서 문자열로 BLOB 데이터를 얻으려고 노력하는 FormData.append 호출에 대한 두 번째 인수로 파일 인스턴스를 사용을 FileReader에 대한 방법, URL.createObjectURL (myBlob)의 값은 불쾌한 밝혀 내 기계를 추락했다.

    나는 모든 솔루션 위뿐만 아니라 관련 답변에 그뿐만 아니라 시도. 솔루션 모두에게 readAs를 호출을 포함하지만 HTMLInputElement의 파일 속성에 수동으로 BLOB 전달에 국한되지 * 얻어서 문자열로 BLOB 데이터를 얻으려고 노력하는 FormData.append 호출에 대한 두 번째 인수로 파일 인스턴스를 사용을 FileReader에 대한 방법, URL.createObjectURL (myBlob)의 값은 불쾌한 밝혀 내 기계를 추락했다.

    당신이 이상의 사람들을 시도하고 아직도 당신이있는 거없는 당신의 덩어리를 업로드 찾을 일이 있다면 지금,이 문제를 의미 할 수 있었다 것은 서버 측이다. 파일이 프론트 엔드를 떠나 그래서 내 경우에는, 내 방울은 php.ini 파일에서 http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize 및 post_max_size을 제한을 초과 형성하지만 서버에서 거부하기. 당신은 직접 php.ini 파일 또는 htaccess로를 통해이 값을 증가시킬 수

  7. from https://stackoverflow.com/questions/13333378/how-can-javascript-upload-a-blob by cc-by-sa and MIT license