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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容