doushi3454
2016-08-04 01:54
浏览 61
已采纳

在require.js模块中上传web生成的图像

I am using a web labeling tool to generate image from the website, however I want to modify the function so that when I am done with labeling, instead of downloading the image to local, I want it to be uploaded into server. The function is in a javascript file and all the upload associated with JS has to do with submitting forms. There is no form and super globals, how am I supposed to upload a web generated image to server?

here is the code I currently have, it is not in html file, it is in js file.

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 file

<?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.';
?>

Really appreciate your help, thank you.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • ds9567 2016-08-04 02:07
    已采纳

    dataURItoBlob(file_data); by the name of the function it looks like that is going to be returning a blob object. blob/file objects when uploaded to a php script are going to be in the $_FILES global, not $_POST. And you would use move_uploaded_file to move it to your desired destination.

    Also you seem to be using the wrong index. You are using hidden_data in your php but you set the name to resultImage in your javascript. You would need to use the same name in php as you did in the javascript.

    So your php code should look something like

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

    As a side note, when using and FormData object you do not need to set the request headers like Content-Type as they will automatically be set by the api.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题