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 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料