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.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据