web直傳oss
.file-box {
position: relative;
display: inline-block;
width: 160px;
height: 160px;
background: url(img/aaa.png) no-repeat;
background-size: cover;
background-position: center;
}
#input_file {
width: 100%;
height: 100%;
opacity: 0;
filter: alpha(opacity=0);
}
oss web服務端簽名後直傳
οnchange="imgPreview(this,0)">
let uploadObj; // 上傳憑證對象
let verifyImg; //上傳之後的圖檔oss位址
function imgPreview(fileDom, i) {
// 擷取上傳憑證
$.ajax({
url: '', // 這裡是請求的背景通過oss上傳憑證的接口
data: JSON.stringify({
data: ''
}),
dataType: 'json',
type: 'post',
headers: {
'Content-Type': 'application/json',
},
success: function(response) {
if (response && response.header.ret == 'S') {
uploadObj = response.data;
// 擷取到上傳憑證成功之後 封裝請求的資料
let request = new FormData();
request.append("OSSAccessKeyId", uploadObj.accessid); //Bucket 擁有者的Access Key Id。
request.append("policy", uploadObj.policy); //policy規定了請求的表單域的合法性
request.append("Signature", uploadObj.signature); //根據Access Key Secret和policy計算的簽名資訊,OSS驗證該簽名資訊進而驗證該Post請求的合法性
//---以上都是阿裡的認證政策
let file = document.getElementById("input_file").files[0];
if (!file) {
return;
}
request.append("key", `${uploadObj.dir}/${file.name}`); //檔案名字,可設定路徑
request.append("success_action_status", '200'); // 讓服務端傳回200,不然,預設會傳回204
request.append('file', file); //需要上傳的檔案 file
$.ajax({
url: uploadObj.host, //上傳阿裡位址
data: request,
processData: false, //預設true,設定為 false,不需要進行序列化處理
cache: false, //設定為false将不會從浏覽器緩存中加載請求資訊
async: false, //發送同步請求
contentType: false, //避免伺服器不能正常解析檔案---------具體的可以查下這些參數的含義
dataType: 'json', //不涉及跨域 寫json即可
type: 'post',
success: function(response) { //callbackHost:success,request中就是 回調的一些資訊,包括狀态碼什麼的
// console.log(response);
},
error: function(error) {
alert("上傳圖檔成功");
verifyImg = `${uploadObj.host}/${uploadObj.dir}/${file.name}`;
}
});
} else {
alert(`${response && response.header.msg[0]}`);
}
},
error: function(error) {
console.log(error);
},
});
console.log(`上傳的檔案oss位址${verifyImg}`);
//判斷是否支援FileReader
if (window.FileReader) {
var reader = new FileReader();
} else {
alert("您的裝置不支援圖檔預覽功能,如需該功能請更新您的裝置!");
}
//擷取檔案
var file = fileDom.files[0];
if (!file) {
return;
}
var imageType = /^image\//;
//是否是圖檔
if (!imageType.test(file.type)) {
alert("請選擇圖檔!");
return;
}
//讀取完成
reader.onload = function(e) {
//圖檔路徑設定為讀取的圖檔
// img.src = e.target.result;
document.getElementsByClassName('file-box')[i].style.background = "url(" + e.target.result + ")no-repeat"; //回顯圖檔
document.getElementsByClassName('file-box')[i].style.backgroundSize = '';
};
reader.readAsDataURL(file);
}
效果如下

項目源碼位址 https://github.com/Pangnz/OssUpload