在test文件夹下建index.html 用于提交图片,do.php用于后端处理
<body>
<center>
<div>
<h4>单图上传至七牛云</h4>
<input type="file" name="file" id='singleImg'>
<button id="single">单图提交</button>
</div>
<div>
<h4>多图上传至七牛云</h4>
<input type="file" name="file" id="moreImg">
<button id="more">多图提交</button>
</div>
<div>
<h4>富文本编辑器多图上传至七牛云</h4>
<input type="file" name="file">
<button>提交</button>
</div>
</center>
</body>
引入七牛云
1、第一种方法
(1)安装composer
(2)在test文件夹下打开命令框 php -r “readfile(‘https://getcomposer.org/installer‘);” | php
会生成一个
文件
(3)php composer.phar require qiniu/php-sdk 安装七牛云的安装包 稍等一小会儿 会成圣vender的文件夹和composer.json
安装成功
2、直接下载vender安装包 效果和上班的下载一样
3、直接安装七牛云的安装包,但是不能更新 直接官网下载PHP-sdk
do.php文件处理
<?php
//引入composer自动加载问价
require 'vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
//这两个秘钥在七牛云后台找
$accessKey = 'iFj';
$secretKey = 'AK';
$auth = new Auth($accessKey, $secretKey);
//shop是我在后台建的分区,专门放这个网站的空间,名字是自己起的
$bucket = 'shop';
// 生成上传Token
$token = $auth->uploadToken($bucket);
//ajax跨域方法。生成json传递给前端
header('Content-Type:application/json');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization');
exit(json_encode(['type' => 'ok', 'message' => $token], JSON_UNESCAPED_UNICODE));
?>
单图上传的jq
$('#single').click(function(){
$.ajax({
url: 'do.php',
type: 'POST',
async: true,
success: function (res) {
var qntoken = res.message;
//获取图片的值,目前没找到合适的jq操作,只能用js原生方法
var file = document.getElementById("singleImg");
console.log(file.files);
//实例化图片格式
formPic = new FormData();
formPic.append('file', file.files[0]);
formPic.append('token',qntoken);
$.ajax({
url: 'https://up-z1.qiniup.com',
type: 'post',
data: formPic,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
//返回的数据是一个字符串
}
});
}
});
});
多图上传的jq
$('#more').click(function(){
$.ajax({
url: 'do.php',
type: 'POST',
async: true,
success: function (res) {
var qntoken = res.message;
var file = document.getElementById("moreImg");
for (var i = 0; i < file.files.length; i++) {
formPic = new FormData();
formPic.append('file', file.files[i]);
formPic.append('token', qntoken);
$.ajax({
url: 'https://up-z1.qiniup.com',
type: 'post',
data: formPic,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
}
}
});
});