SimpleHTTPServerWithUpload.py通过javascript

时间:2016-12-23 17:42:59

标签: javascript python-2.7

..使用SimpleHTTPServerWithUpload.py(或其任何分支) https://gist.github.com/arulrajnet/af376482bbe95346824e419b7c9cbdd0

..使用curl工作正常:即curl -F file=@/path/file.ext localhost:8000

..但是在通过javascript提交时似乎无法正确获取标题,我会收到各种错误/挂起,具体取决于标头的设置/未设置方式。尝试了数百种组合,在图像创建和提交之间增加了超时但没有快乐。

..我是job job的noob,甚至更少w / python,所以无法真正告诉SimpleHTTPServerWithUpload期待什么。

function sendBase64ToServer(name){

// make a canvas and fill it
var mycanvas = document.createElement("canvas");
document.body.appendChild(mycanvas);
var context = mycanvas.getContext("2d");
context.rect(0, 0, 80, 80);
context.fillStyle = 'yellow';
context.fill();

// convert to base64 data
var dataURL = mycanvas.toDataURL("image/png");

var url = "http://localhost:8000";
var httpPost = new XMLHttpRequest();
    httpPost.open("POST", url, true);

// Set headers ..tried all/every combination
//httpPost.setRequestHeader("Content-Type", "multipart/form-data");
//httpPost.setRequestHeader("Content-enctype", "multipart/form-data");
//httpPost.setRequestHeader("ENCTYPE", "multipart/form-data");
//httpPost.setRequestHeader("Cache-Control", "no-cache");
//httpPost.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//httpPost.setRequestHeader("X-File-Name", name);
//httpPost.setRequestHeader("X-File-Size", dataURL.length);
//httpPost.setRequestHeader("X-File-Type", 'image/png');

httpPost.send(dataURL);

}

..甚至尝试先转换为json ..但仍然没有

var data = JSON.stringify({image: dataURL});
var httpPost = new XMLHttpRequest();    
httpPost.open("POST", url, true);
// various header settings here too
httpPost.send(data);

2 个答案:

答案 0 :(得分:0)

尝试发送Blob

httpPost.send(new Blob([dataURL], { type: "image/png" }));

我相信应该为您做所有必需的接线。您可能需要在此答案中转换数据uri:https://stackoverflow.com/a/5100158/724626

答案 1 :(得分:0)

终于明白了。使它发挥作用的两件事。 1.需要根据Joe https://stackoverflow.com/a/5100158/724626以上建议的链接将blob转换为更多二进制文件.2。SimpleHTTPServerWithUpload期待"文件"不只是数据。

这是任何感兴趣的人的完整示例。留下原始问题,因为记录哪些不起作用可能是有用的。

function sendBase64ToServer(name){

// make a canvas and fill it
var mycanvas = document.createElement("canvas");
document.body.appendChild(mycanvas);
var context = mycanvas.getContext("2d");
context.rect(0, 0, 80, 80);
context.fillStyle = 'yellow';
context.fill();

var dataUrl = mycanvas.toDataURL();

// convert base64/URLEncoded data to raw binary data held in a string
var blob = dataURItoBlob(dataUrl);

// SimpleHTTPServerWithUpload is expecting a "File"
var fileOfBlob = new File([blob], 'testSave.png'); 

// add the file to a form
var formData = new FormData();
    formData.append("file", fileOfBlob);

// send it
var url = "http://localhost:8000";
var httpPost = new XMLHttpRequest();
    httpPost.open("POST", url, true);
    httpPost.send(formData);

}