자바스크립트는 어떻게 블롭을 업로드 할 수 있습니까?
이 구조에 블롭 데이터가 있습니다.
Blob {type: "audio/wav", size: 655404, slice: function}
size: 655404
type: "audio/wav"
__proto__: Blob
최근 크롬을 사용해 녹음한 음성 데이터입니다.getUerMedia()그리고 Recorder.js
jquery의 post method로 이 blob을 서버에 업로드하려면 어떻게 해야 합니까?운도 없이 해봤어요.
$.post('http://localhost/upload.php', { fname: "test.wav", data: soundBlob },
function(responseText) {
console.log(responseText);
});
FormData API를 이용하시면 됩니다.
사용하시는 경우jquery.ajax, 설정해야 합니다.processData: false그리고.contentType: false.
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);
});
2019년 업데이트
이것은 최신 Fetch API로 답변을 업데이트하며 jQuery가 필요하지 않습니다.
면책 사항: IE, Opera Mini 및 이전 브라우저에서는 작동하지 않습니다.캐니유즈를 보세요.
기본 가져오기
다음과 같이 간단할 수 있습니다.
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 코드
업로드중인서버측코드입니다.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);
?>
당신은 사실 사용할 필요가 없습니다.FormData부치다Blob자바스크립트(및 a)에서 서버로.File또한.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);
기실, 전통적인 HTML 멀티파트 양식을 "AJAX" 구현으로 대체하는 경우(즉, 백엔드가 멀티파트 양식 데이터를 소비하는 경우),FormData다른 답변에 설명된 개체입니다.
출처: XMLHttpRequest2의 새로운 트릭 | HTML5 Rocks
blobs와 함께 작업할 위의 예시를 얻을 수 없었고 업로드 중인 것이 정확히 무엇인지 알고 싶었습니다.자, 여기 있습니다.
(Chrome 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);
}
업로드한 내용.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);
?>
FormData를 사용하지 않고 javascript object를 사용하여 blob을 전송함으로써 @yeeking 예제를 작동시킬 수 있었습니다.recorder.js를 사용하여 생성된 사운드 블롭으로 작동합니다.Chrome 버전 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);
?>
저는 위의 모든 해결책과 더불어 관련된 답변들도 시도해 보았습니다.Blob을 수동으로 HTMLInputElement의 파일 속성에 전달하고, FileReader의 모든 readAs* 메서드를 호출하고, FormData.append 호출에 대한 두 번째 인수로 File 인스턴스를 사용하여 URL의 값을 가져와 Blob 데이터를 문자열로 가져오도록 하는 것을 포함하지만 이에 국한되지 않습니다.내 기계를 부수고 끔찍한 결과를 낳은 ObjectURL(myBlob)을 생성합니다.
만약 그 이상의 시도를 했는데도 블롭을 업로드할 수 없다는 것을 알게 된다면 문제는 서버 쪽에 있다는 것을 의미할 수 있습니다.저의 경우, 제 blob이 PHP에서 http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize 및 post_max_size 제한을 초과했습니다.INI로 인해 파일이 프론트엔드 양식에서 이탈하고 있었지만 서버에서 거부당했습니다.이 값을 직접 PHP로 올릴 수도 있습니다.INI 또는 .htaccess 경유
언급URL : https://stackoverflow.com/questions/13333378/how-can-javascript-upload-a-blob
'programing' 카테고리의 다른 글
| Google Chrome form autofill 및 노란색 배경 (0) | 2023.10.21 |
|---|---|
| 마리아드브 갈레라 성단과 캡 정리 (0) | 2023.10.21 |
| 상위 범위가 지정된 Angularjs에서 모든 하위 범위를 가져옵니다. (0) | 2023.10.21 |
| 루트가 아닌 하위 디렉토리에서 워드프레스 실행 (0) | 2023.10.21 |
| JPA 외부 키 0 값 최대 절전 모드 과도 속성 값 예외 (0) | 2023.10.21 |