带你玩转七牛云存储——高级篇

前端开发 作者: 2024-08-21 05:35:01
七牛云图片存储优点 1. 支持各种尺寸的图片缩放; 2. 支持图片自动压缩; 3. 支持水印添加:图片水印、文字水印两种模式; 2. 图片防盗链,限制访问来源; 2. 设置ip黑白名单,防止恶意盗刷、

七牛云图片存储优点

  1. 支持各种尺寸的图片缩放;
  2. 支持图片自动压缩;
  3. 支持水印添加:图片水印、文字水印两种模式;
  4. 图片防盗链,限制访问来源;
  5. 设置ip黑白名单,防止恶意盗刷、攻击;
  6. 自定义图片域名,看起来更具有归属性;
  7. 统计图片的各种访问数据;
  8. 支持上传日志文件,可保存30天,便于排除程序问题;

水印

图片处理

图片上传

上传步骤

  1. 根据AccessKey + SecretKey (可在个人中心=》秘钥管理查看) + bucket(存储空间名称),生成token;
  2. 使用图片源(文件流/文件地址)和token提交信息到七牛存储图片;

上传途径

  1. 服务器端上传:分为本地文件上传、字节数组上传;
  2. 客户端上传:Base64模式上传、Blob模式上传;

服务器端-nodejs上传

  1. 使用npm安装七牛SDK:
  1. 使用下面代码获取uploadToken:
var accessKey = 'xxx'; //可在个人中心=》秘钥管理查看
var secretKey = 'xxx'; //可在个人中心=》秘钥管理查看
var bucket = "apigo";  //存储空间名称
var mac = new qiniu.auth.digest.Mac(accessKey,secretKey);
var options = {
  scope: bucket
}
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);
return this.jsonp({ 'token': uploadToken });
var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1; // 空间对应的机房
var formUploader = new qiniu.form_up.FormUploader(config);
var putExtra = new qiniu.form_up.PutExtra();

var key='test.png';  //上传到服务器的名称
var localFile = "D:\\img\\test.png"; // 本地文件路径
formUploader.putFile(uploadToken,key,localFile,putExtra,function (respErr,respBody,respInfo) {
  if (respErr) {
    throw respErr;
  }
  if (respInfo.statusCode == 200) {
    console.log(respBody);
  } else {
    console.log(respInfo.statusCode);
    console.log(respBody);
  }
});
  • 华东 qiniu.zone.Zone_z0
  • 华北 qiniu.zone.Zone_z1
  • 华南 qiniu.zone.Zone_z2
  • 北美 qiniu.zone.Zone_na0
<form action="http://127.0.0.1:8360/qiniu/upload" method="POST" enctype="multipart/form-data">
    <input name="f" type="file" />
    <button type="submit">提交</button>
</form>
var _file = this.file("f"); //前台type=file post过来的文件
var putExtra = new qiniu.form_up.PutExtra();
var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1; // 空间对应的机房
var formUploader = new qiniu.form_up.FormUploader(config);
var key = "test1.png";
var readStream = fs.createReadStream(_file.path); //文件流对象
formUploader.putStream(uploadToken,readStream,respInfo) {
  if (respErr) {
    throw respErr;
  }
  if (respInfo.statusCode == 200) {
    console.log(respBody);
  } else {
    console.log(respInfo.statusCode);
    console.log(respBody);
  }
});
import { Duplex } from 'stream';

var b64string = 'xxx';   //base64必须去掉头文件(data:image/png;base64,)
var buff = new Buffer(b64string,'base64')
var stream = new Duplex();
stream.push(buff);
stream.push(null);

var putExtra = new qiniu.form_up.PutExtra();
var config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1; // 空间对应的机房
var formUploader = new qiniu.form_up.FormUploader(config);
var key = "test.png";
formUploader.putStream(uploadToken,stream,respInfo) {
  if (respErr) {
    throw respErr;
  }
  if (respInfo.statusCode == 200) {
    console.log(respBody);
  } else {
    console.log(respInfo.statusCode);
    console.log(respBody);
  }
});

客户端-javascript上传

<script type="text/javascript" src="https://unpkg.com/qiniu-js@2.3.0/dist/qiniu.min.js"></script>
//base64模式直接上传
var base64 = 'xxx'.replace('data:image/png;base64,','');
var imgName = toBase64('xxx.png'); //自定义文件名必须是base64格式的
var url = "http://upload.qiniup.com/putb64/-1/key/" + imgName; //非华东空间需要根据注意事项-修改上传域名(upload.qiniup.com)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        //上传成功,返回信息
        console.log(xhr.responseText);
    }
}
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type","application/octet-stream");
xhr.setRequestHeader("Authorization","UpToken " + uploadToken);
xhr.send(base64);


function toBase64(data) {
	var toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
	var base64Pad = '=';
    var result = '';
    var length = data.length;
    var i;
    // Convert every three bytes to 4 ascii characters.                                                   

    for (i = 0; i < (length - 2); i += 3) {
        result += toBase64Table[data.charCodeAt(i) >> 2];
        result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
        result += toBase64Table[((data.charCodeAt(i + 1) & 0x0f) << 2) + (data.charCodeAt(i + 2) >> 6)];
        result += toBase64Table[data.charCodeAt(i + 2) & 0x3f];
    }

    // Convert the remaining 1 or 2 bytes,pad out to 4 characters.     
    if (length % 3) {
        i = length - (length % 3);
        result += toBase64Table[data.charCodeAt(i) >> 2];
        if ((length % 3) == 2) {
            result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
            result += toBase64Table[(data.charCodeAt(i + 1) & 0x0f) << 2];
            result += base64Pad;
        } else {
            result += toBase64Table[(data.charCodeAt(i) & 0x03) << 4];
            result += base64Pad + base64Pad;
        }
    }
    return result;
}
  1. url参数注意空间存储区域,不同地域url地址不同,华东upload.qiniup.com,华北upload-z1.qiniu.com,华南upload-z2.qiniu.com,北美upload-na0.qiniu.com;
  2. 文件名(imgName)必须是base64格式的;
  3. 请求头Authorization的值格式:"UpToken " + uploadToken(服务器端获取uploadToken,见上文);
var putExtra = {
    fname: "",params: {},mimeType: [] || null
};
var config = {
    useCdnDomain: true
};

// base64 转 blob 模式上传
var base64 = 'xxx'.replace('data:image/png;base64,'');
var contentType = 'image/png';
var blob = base64ToBlob(base64,contentType,undefined);
var observable = qiniu.upload(blob,'xxx.png',qiniuToken,config);
var subscription = observable.subscribe({
    next(res) {
        // console.log(res);
    },error(err) {
        console.log(err);
    },complete(res) {
        console.log(res);
    }
});

//base64转blob
function base64ToBlob(base64,sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;
    var byteCharacters = atob(base64);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset,offset + sliceSize);
        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    var blob = new Blob(byteArrays,{ type: contentType });
    return blob;
}

开启你的使用之旅吧

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65924.html