js上传文件php处理,PHP + JS:如何以HTML形式将文件上传为Content-Type Multipart(通过JS)?...

小编典典

您可以使用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);

}

2020-05-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值