oss大文件网页上传

支持超大文件上传,经过测试网页直传比java后台传速度快很多,亲测有效

js代码

<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.0.2.min.js"></script>
<script th:inline="javascript">
    var prefix = ctx + "web/ota"
    $("#form-ota-add").validate({
        focusCleanup: true
    });

    var upfiles = [];
    $(function () {
        //初始化文件上传队列
        $("#firmware").change(function (e) {
            var ufiles = $(this).prop('files');
            for (var i = 0; i < ufiles.length; i++) {
                upfiles.push({
                    num: i,
                    name: ufiles[i].name,
                    file: ufiles[i]
                })
            }
            console.log('upfiles:', upfiles);
        })
    })

 // 初始化加载client对象  为了不暴露自己的 accessKeyId 和 accessKeySecret需要请求接口去获取临时的
    var appServer = 'http://192.168.110.136/web/ota/credential'; //请求接口获取数据 
    var bucket = '你的bucket名称';  // bucket名称
    var region = 'oss-cn-shenzhen'; // 地区
    var urllib = OSS.urllib;
    var Buffer = OSS.Buffer;
    var OSS = OSS;
    var md5 = '';
    var applyTokenDo = function (func) {
        var url = appServer;
        return urllib.request(url, {
            method: 'GET'
        }).then(function (result) {
            var creds = JSON.parse(result.data);
            console.log(creds);
            var client = new OSS({
                region: region,
                accessKeyId: creds.keyId, //访问密钥标识
                accessKeySecret: creds.keySecret, // 访问密钥
                stsToken: creds.securityToken, // 安全令牌
                bucket: bucket,
            });
            return func(client);
        });
    };

    // 上传文件 并且计算进度,以进度条方式展示
    var uploadFile = function (client) {
        console.log(client);
        if (upfiles.length < 1) {
            return;
        }
        var timestamp = (new Date()).valueOf();
        upfile = upfiles[0];
        var file = upfile.file;
        var key = upfile.name;
        var suffix = 'ota/' + timestamp + key.substring(key.length - 4);
        return client.multipartUpload(suffix, file, {
            progress: function (p, cpt, res) {
                let ps = parseInt((p.toFixed(2)) * 100);
                console.log("上传进度:", ps + '%');
                console.log("cpt:", cpt);
                let html = '';
                // 进度条循环赋值
                html = '<dl><dt></dt><dd><div class="progress"><div  class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:' + ps + '%"><span>' + ps + '%</span></div></div></dd></dl>';
                $("#up_wrap").html(html);
                // 计算进度 当p等于1说明上传完成
                if (p == 1) {
                  // 最终上传完成后的下载url
                    const url = `https://${bucket}.${region}.aliyuncs.com/${suffix}`; 
                    console.log("url:", url); 
                    $("#ossKey").val(suffix); // osskey (删除文件的话需要这个)
                    $("#downloadUrl").val(url); // 下载地址
                    $("#fileSize").val(file.size); // 文件大小
                    // 表单提交
                    if ($.validate.form()) {
                        $.operate.save(prefix + "/add", $('#form-ota-add').serialize());
                    }
                }
                if (cpt != undefined) {
                    var content = JSON.stringify(cpt);
                    client.put(suffix, new Buffer(content));
                }
                return function (done) {
                    var bar = document.getElementById('progress-bar_' + upfile.num);
                    bar.style.width = Math.floor(p * 100) + '%';
                    bar.innerHTML = Math.floor(p * 100) + '%';
                    done();
                }
            }
        }).then(function (res) {
            console.log('上传成功: ', res);
            upfiles.shift();
            client.delete(key);
            applyTokenDo(uploadFile);
        });
    };
    function submitHandler() {
        applyTokenDo(uploadFile);
    }

</script>

HTML

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增ota文件')"/>
    <th:block th:include="include :: jasny-bootstrap-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-ota-add" enctype="multipart/form-data">
        <input name="ossKey" id="ossKey" type="hidden">
        <input name="downloadUrl" id="downloadUrl" type="hidden">
        <input name="fileSize" id="fileSize" type="hidden">
        <input name="otaMd5" id="otaMd5" type="hidden">
        <div class="form-group">
            <label class="col-sm-3 control-label">ota名字:</label>
            <div class="col-sm-8">
                <input name="otaName" required class="form-control" type="text">
            </div>
        </div>


        <div class="form-group">
            <label class="col-sm-3 control-label">大版本号:</label>
            <div class="col-sm-8">
                <input name="version" required class="form-control" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">二级版本号:</label>
            <div class="col-sm-8">
                <input name="subVersion" required class="form-control" type="text">
            </div>
        </div>


        <div class="form-group">
            <label class="col-sm-3 control-label">版本标识:</label>
            <div class="col-sm-8">
                <select class="form-control" required name="versionIdentification">
                    <option value="">请选择</option>
                    <option value="Beta">Beta</option>
                    <option value="Release">Release</option>
                </select>
            </div>
        </div>


        <div class="form-group">
            <label class="col-sm-3 control-label">产品型号:</label>
            <div class="col-sm-8">
                <select name="model" required class="form-control m-b"
                        th:with="type=${@dict.getType('im_system_ota_model')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>


        <div class="form-group">
            <label class="col-sm-3 control-label">平台代号:</label>
            <div class="col-sm-8">
                <select name="platformCode" required class="form-control m-b"
                        th:with="type=${@dict.getType('im_system_ota_platform_code')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">地区:</label>
            <div class="col-sm-8">
                <select name="region" required class="form-control m-b"
                        th:with="type=${@dict.getType('im_system_ota_region')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">更新内容:</label>
            <div class="col-sm-8">
                <textarea name="note" required maxlength="600" class="form-control" rows="3"></textarea>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">选择ota包:</label>
            <div class="fileinput fileinput-new col-sm-8" data-provides="fileinput">
                    <span class="btn btn-white btn-file"><span class="fileinput-new">选择ota包</span><span
                            class="fileinput-exists">更改</span>
                        <input type="file" id="firmware" required multiple="multiple"/>
                    </span>
                <span class="fileinput-filename"></span>
                <a href="#" class="close fileinput-exists" data-dismiss="fileinput" style="float: none">&times;</a>
            </div>
        </div>

        <!-- 进度条展示   -->
        <div id="up_wrap" style="margin-left: 190px;width: 480px;"></div>
    </form>
</div>

Controller

@Controller
@RequestMapping("/web/ota")
public class ImSystemOtaController extends BaseController {
    private String prefix = "web/ota";
     /**
     * 获取临时token
     */
    @GetMapping("/credential")
    @ResponseBody
    @CrossOrigin
    public StsTokenVO credential() {
        return OssGetStsToken.getStsToken();
    }
   }

获取STStoken接口

public class OssGetStsToken {

    private static final Logger log = LoggerFactory.getLogger(OssGetStsToken.class);
    private static String accessKeyId = "你的accessKeyId ";

    private static String accessKeySecret = "你的accessKeySecret ";

	// 阿里云控制台 RAM 访问控制里面添加 (自行百度如何创建)
    private static String roleArn = "roleArn";
    
	// 你的角色名字
    private static String roleSess	ionName = "角色名字";
    /**
     * token失效时间,单位秒(不设置默认1小时,这里设置5分钟)
     */
    private static final Long durationSeconds = 1200L;
    private static final String ENDPOINT = "sts.aliyuncs.com";

    /**
     * 获取STStoken接口
     *
     * @param:
     * @return: StsTokenVO
     */
    public static StsTokenVO getStsToken() {
        StsTokenVO tokenVO = new StsTokenVO();
        try {
            // 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
            DefaultProfile.addEndpoint("", "", "Sts", ENDPOINT);
            // 构造default profile(参数留空,无需添加region ID)
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            // request.setDurationSeconds(durationSeconds);
            // 针对该临时权限可以根据该属性赋予规则,格式为json,没有特殊要求,默认为空
            // request.setPolicy(policy); // Optional
            final AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            tokenVO.setKeyId(credentials.getAccessKeyId());
            tokenVO.setKeySecret(credentials.getAccessKeySecret());
            tokenVO.setSecurityToken(credentials.getSecurityToken());
            return tokenVO;
        } catch (ClientException e) {
            log.error("获取阿里云STS临时授权权限失败,错误信息:" + e);
            return null;
        }
    }
}

StsTokenVO

@Data
public class StsTokenVO implements Serializable {

    /**
     * 访问密钥标识
     */
    private String keyId;
    /**
     * 访问密钥
     */
    private String keySecret;
    /**
     * 安全令牌
     */
    private String securityToken;

}

上传页面展示

页面展示

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值