前端上传图片到七牛

demo地址:https://download.csdn.net/download/a707369808/10572165
uploadPic(fileArr[0], 1);//上传图片
// 上传设置
var config = {
    useCdnDomain: true,
    region: null
};
/**
     * 往七牛上传图片
     * @param file 文件
     * @param key 递归用,下个上传文件的索引
     */
    function uploadPic(file, key) {
        $.ajax({
            url: root + "/commonUploadOrDownload/makeTokenByZhoti.shtml",//获取token接口
            dataType: 'json',
            success: function (data) {
                // console.log(data);
                var observable = qiniu.upload(file, uuid(), data.uptoken, {fname: file.name}, config);
                var subscription = observable.subscribe({
                    error: function (err) {
                        console.log(err);
                        qiNiuKey = [];
                    },
                    complete: function (res) {
                        qiNiuKey.push(res.key);
                        if (key < fileArr.length) {
                            uploadPic(fileArr[key], key + 1)
                        } else {
                            console.log("上传成功");
                            submit()
                        }
                    }
                });
            },
            error: function (err) {
                alert("网络错误");
            }
        });
    }
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    var uu = s.join("");
    return uu;
}
前端生成七牛云的上传凭证(token)一般需要结合后端来完成,因为生成凭证需要使用七牛云的密钥,为了安全起见,密钥一般保存在后端,前端通过与后端的交互获取凭证。 以下是一个前端与后端结合生成七牛上传凭证并上传图片的示例: 1. 后端代码(Node.js): ```javascript const qiniu = require('qiniu'); const accessKey = 'YOUR_QINIU_ACCESS_KEY'; const secretKey = 'YOUR_QINIU_SECRET_KEY'; function generateQiniuToken() { const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); const options = { scope: 'YOUR_QINIU_BUCKET_NAME', expires: 3600, // 凭证有效时间,单位:秒 }; const putPolicy = new qiniu.rs.PutPolicy(options); const uploadToken = putPolicy.uploadToken(mac); return uploadToken; } // 在路由处理函数中返回生成的上传凭证给前端 app.get('/qiniu/token', (req, res) => { const token = generateQiniuToken(); res.json({ token }); }); ``` 上述代码使用了qiniu-sdk库来生成七牛上传凭证。你需要替换YOUR_QINIU_ACCESS_KEY、YOUR_QINIU_SECRET_KEY和YOUR_QINIU_BUCKET_NAME为你自己的七牛云密钥和存储空间名称。 2. 前端代码(Vue.js): ```javascript import axios from 'axios'; methods: { uploadImage() { uni.chooseImage({ success: (res) => { const tempFilePaths = res.tempFilePaths; this.getQiniuTokenAndUpload(tempFilePaths[0]); }, }); }, getQiniuTokenAndUpload(filePath) { axios.get('/qiniu/token') // 向后端请求获取上传凭证 .then((response) => { const token = response.data.token; this.uploadToQiniu(token, filePath); }) .catch((error) => { console.log(error); }); }, uploadToQiniu(token, filePath) { const url = 'https://upload.qiniup.com'; const key = Date.now() + '.jpg'; // 设置文件名,这里使用当前时间戳作为文件名 uni.uploadFile({ url, filePath, name: 'file', formData: { token, key, }, success: (res) => { // 上传成功,处理返回的数据 console.log(res.data); }, fail: (err) => { // 上传失败,处理错误信息 console.log(err); }, }); }, } ``` 上述代码使用了axios库发送GET请求获取后端生成的上传凭证,然后调用uni.uploadFile方法将图片上传七牛云存储。 请确保替换YOUR_QINIU_ACCESS_KEY、YOUR_QINIU_SECRET_KEY和YOUR_QINIU_BUCKET_NAME为你自己的七牛云密钥和存储空间名称。同时,你还需要根据实际情况修改后端路由路径和前端请求路径。 这样,当用户点击按钮时,前端会通过后端获取七牛云的上传凭证,并将选择的图片上传七牛云存储中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值