在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);
}
});
}
}
});
});