支持超大文件上传,经过测试网页直传比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);
})
})
var appServer = 'http://192.168.110.136/web/ota/credential';
var 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);
if (p == 1) {
const url = `https://${bucket}.${region}.aliyuncs.com/${suffix}`;
console.log("url:", url);
$("#ossKey").val(suffix);
$("#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">×</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";
@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 ";
private static String roleArn = "roleArn";
private static String roleSess ionName = "角色名字";
private static final Long durationSeconds = 1200L;
private static final String ENDPOINT = "sts.aliyuncs.com";
public static StsTokenVO getStsToken() {
StsTokenVO tokenVO = new StsTokenVO();
try {
DefaultProfile.addEndpoint("", "", "Sts", ENDPOINT);
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
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;
}
上传页面展示
![页面展示](https://i-blog.csdnimg.cn/blog_migrate/0b274493ea021f0b75d5cf77968675bc.png)