2016-08-04 1 views
0

웹 라벨링 도구를 사용하여 웹 사이트에서 이미지를 생성하고 있습니다. 그러나 라벨 지정을 마쳤을 때 이미지를 로컬로 다운로드하는 대신, 서버에 업로드하고 싶습니다. 이 함수는 자바 스크립트 파일에 있으며 JS와 관련된 모든 업로드는 양식 제출과 관련이 있습니다. 양식 및 슈퍼 전역 변수가 없습니다. 웹에 생성 된 이미지를 서버에 업로드하려면 어떻게해야합니까?require.js 모듈에 웹 생성 이미지 업로드하기

여기에 제가 현재 가지고있는 코드입니다. HTML 파일이 아니며, js 파일에 있습니다.

var file_data = annotator.export(); 
var formData = dataURItoBlob(file_data); 
var fd = new FormData(document); 
fd.append("resultImage",formData); 
url="upload/"; 
http.open("POST", url, true); 

// headers 
http.setRequestHeader("Content-type", "application/x-www-form-  urlencoded"); 
http.setRequestHeader("Content-length", fd.length); 
http.setRequestHeader("Connection", "close"); 

http.onreadystatechange = function() { 
if(http.readyState == 4 && http.status == 200) { 
    alert(http.responseText); 
} 
} 

http.send(fd); 

PHP 파일은

<?php 
$upload_dir = "upload/"; 
$img = $_POST['hidden_data']; 
$img = str_replace('data:image/png;base64,', '', $img); 
$img = str_replace(' ', '+', $img); 
$data = base64_decode($img); 
$file = $upload_dir . mktime() . ".png"; 
$success = file_put_contents($file, $data); 
print $success ? $file : 'Unable to save the file.'; 
?> 

정말 감사합니다, 당신의 도움을 주셔서 감사합니다.

답변

0

dataURItoBlob(file_data); blob 객체를 반환하는 것처럼 보이는 함수 이름으로 표시합니다. PHP 스크립트로 업로드 할 때 blob/file 객체는 $_FILES이 아니며 $_POST이 아닙니다. 원하는 위치로 이동하려면 move_uploaded_file을 사용합니다.

또한 잘못된 색인을 사용하고있는 것 같습니다. 귀하의 PHP에서 hidden_data을 사용하고 있지만 귀하의 자바 스크립트에 resultImage의 이름을 설정합니다. 당신은 자바 스크립트에서했던 것처럼 PHP에서 같은 이름을 사용해야 할 것이다.

그래서 PHP 코드는 보조 노트로서

$upload_dir = "upload/"; 
$img = $_FILES['resultImage']; 
if($img["error"] == UPLOAD_ERR_OK){ 
    //should do other sanitation like making sure the file 
    //that is uploaded is the actual type of file you expect 
    $path = $upload_dir . mktime() . ".png"; 
    move_uploaded_file($img["tmp_name"], $path); 
} 

처럼 보일 것이다 사용하고 FormData 당신이 그들이 자동으로 API에 의해 설정 될 것이다 Content-Type 같은 요청 헤더를 설정할 필요가 없습니다 객체 때.

+0

감사합니다. 에반스, 미안하지만 아직 upvote에 대한 충분한 명성이 없습니다. –

관련 문제