1 回答
![?](http://img1.sycdn.imooc.com/5458463b0001358f02200220-100-100.jpg)
TA贡献1993条经验 获得超5个赞
您可以使用FormData对象获取表单的值,然后将画布的Blob版本附加到FormData中。
该斑点将被服务器视为文件。
不幸的是,所有浏览器仍然不支持本机canvas.toBlob()方法,甚至值得,所有实现都不相同。
现在,所有主要的浏览器都支持toBlob方法,并且您可以在mdn上为较旧的浏览器找到一个 polyfill。
// the function to create and send our FormData
var send = function(form, url, canvas, filename, type, quality, callback) {
canvas.toBlob(function(blob){
var formData = form ? new FormData(form) : new FormData();
formData.append('file', blob, filename);
var xhr = new XMLHttpRequest();
xhr.onload = callback;
xhr.open('POST', url);
xhr.send(formData);
}, type, quality);
};
// How to use it //
var form = document.querySelector('form'), // the form to construct the FormData, can be null or undefined to send only the image
url = 'http://example.com/upload.php', // required, the url where we'll send it
canvas = document.querySelector('canvas'), // required, the canvas to send
filename = (new Date()).getTime() + '.jpg',// required, a filename
type = 'image/jpeg', // optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'
quality = .5, // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding
callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finished
send(form, url, canvas, filename, type, quality, callback);
PHP方面将是:
if ( isset( $_FILES["file"] ) ){
$dir = 'some/dir/';
$blob = file_get_contents($_FILES["file"]['tmp_name']);
file_put_contents($dir.$_FILES["file"]["name"], $blob);
}
添加回答
举报