阿里oss文件上传

2018-02-27 11:04:37来源:oschina作者:林伟琨人点击

分享

java代码
上传参数


```
##阿里云oss上传 参数 (注意 endpoint的格式形如“http://oss-cn-hangzhou.aliyuncs.com/”,注意http://后不带bucket名称,)
oss_access_key =LTAI6ScalfVxxxx
oss_access_key_secret =LFWF9MdYnHpFpU0ZU5R55tqvADxxx
oss_showEndpoint =http://xxx.oss-cn-beijing.aliyuncs.com/
oss_endpoint =oss-cn-beijing.aliyuncs.com
oss_bucket_name =xxx
oss_folder =xxx/
oss_folder_video =video/
//阿里云API显示路径
@Value("${oss_showEndpoint}")
private String ossShowEndpoint ;
//阿里云API上传路径
@Value("${oss_endpoint}")
private String ossEndpoint ;
//阿里云API的密钥Access Key ID
@Value("${oss_access_key}")
private String ossAccessKey;
//阿里云API的密钥Access Key Secret
@Value("${oss_access_key_secret}")
private String ossAccessKeySecret;
//阿里云API的bucket名称
@Value("${oss_bucket_name}")
private String ossBacketName;
//阿里云API的文件夹名称
@Value("${oss_folder}")
private String ossFolder;
//阿里云API的文件夹名称
@Value("${oss_folder_video}")
private String ossFolderVideo;
@Action(value = "/video/video/getSnt", results = {@Result(name = JSON, type = JSON, params = {"root", "result"})})
public String get() {
//TODO 文件名重复--oss那边会自动查重
String endpoint = settings.getOssEndpoint();
String accessId = settings.getOssAccessKey();
String accessKey = settings.getOssAccessKeySecret();
String dir = settings.getOssFolder()+settings.getOssFolderVideo();
String host = settings.getOssShowEndpoint();
OSSClient client = new OSSClient(endpoint, accessId, accessKey);
try {
long expireTime = 1*60*60;//1小时
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = client.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = client.calculatePostSignature(postPolicy);
Map respMap = new LinkedHashMap();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir+FORMAT+"/");
respMap.put("host", host);
respMap.put("expire", formatISO8601Date(expiration));
resultMessage(respMap);


//TODO 回调测试 本地测试回调地址进不来
Map backUrlMap = new LinkedHashMap();
backUrlMap.put("callbackUrl", "xxx.top:8081/common/console/index.action");//这边的action进不来 先不做
backUrlMap.put("callbackHost", "xxx.top");
backUrlMap.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
backUrlMap.put("callbackBodyType", "application/x-www-form-urlencoded");

JSONObject backUrlString = JSONObject.fromObject(backUrlMap);
final Base64 base64 = new Base64();
final byte[] textByte = backUrlString.toString().getBytes("UTF-8");
//编码
final String encodedText = base64.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(base64.decode(encodedText), "UTF-8"));

//TODO 增加oss管理 需要判断前端这个文件是否正确上传(前后端都要回调方法)
} catch (Exception e) {
Assert.fail(e.getMessage());
resultMessage(FAIL, e.getMessage());
}
return JSON;
}private String formatISO8601Date(Date expiration) {
String pattern = "yyyy-MM-dd'T'HH:mm:ss:SSSZZ";
return DateFormatUtils.format(expiration, pattern);
}
js
```
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;
function send_request()
{
var xmlhttp = null;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

if (xmlhttp!=null)
{
serverUrl = '/video/video/getSnt.action'
xmlhttp.open( "GET", serverUrl, false );
xmlhttp.send( null );
return xmlhttp.responseText
}
else
{
alert("您的浏览器不支持XMLHTTP,建议使用谷歌浏览器");
}
};
function check_object_radio() {
var tt = document.getElementsByName('myradio');
for (var i = 0; i < tt.length ; i++ )
{
if(tt[i].checked)
{
g_object_name_type = tt[i].value;
break;
}
}
}
function get_signature()
{
//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
now = timestamp = Date.parse(new Date()) / 1000;
if (expire < now + 3)
{
body = send_request()
var obj = eval ("(" + body + ")");
host = obj['host']
policyBase64 = obj['policy']
accessid = obj['accessid']
signature = obj['signature']
expire = parseInt(obj['expire'])
callbackbody = obj['callback']
key = obj['dir']
return true;
}
return false;
};
function random_string(len) {
len = len || 32;
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var maxPos = chars.length;
var pwd = '';
for (i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
function get_suffix(filename) {
pos = filename.lastIndexOf('.')
suffix = ''
if (pos != -1) {
suffix = filename.substring(pos)
}
return suffix;
}
function calculate_object_name(filename)
{
if (g_object_name_type == 'local_name')
{
g_object_name += "${filename}"
}
else if (g_object_name_type == 'random_name')
{
suffix = get_suffix(filename)
g_object_name = key + random_string(10) + suffix
}
return ''
}
function get_uploaded_object_name(filename)
{
if (g_object_name_type == 'local_name')
{
tmp_name = g_object_name
tmp_name = tmp_name.replace("${filename}", filename);
return tmp_name
}
else if(g_object_name_type == 'random_name')
{
return g_object_name
}
}


function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function set_upload_param(up, filename, ret)
{
if (ret == false)
{
ret = get_signature()
}
g_object_name = key;
if (filename != '') {
suffix = get_suffix(filename)
calculate_object_name(filename)
}
new_multipart_params = {
'key' : g_object_name,
'policy': policyBase64,
'OSSAccessKeyId': accessid,
'success_action_status' : '200', //让服务端返回200,不然,默认会返回204
'callback' : callbackbody,
'signature': signature,
};
up.setOption({
'url': host,
'multipart_params': new_multipart_params
});
up.start();
}

function video_upload_cancel(file_id) {//取消上传
uploader.stop();
var obj_file = uploader.getFile(file_id.id);
uploader.removeFile(obj_file);
var $fileDelete=$("#"+file_id.id);
$fileDelete.remove();
}


function video_upload_delete(file_id) {//删除视频
var obj_file = uploader.getFile(file_id.id);
var fileName=host+get_uploaded_object_name(obj_file.name);
business.video.deleteVideo(fileName);
uploader.removeFile(obj_file);
var $fileDelete=$("#"+file_id.id);
$fileDelete.remove();
} var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'selectfiles',
multi_selection: false,
container: document.getElementById('container'),
flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
url : 'http://oss.aliyuncs.com',
filters: {
mime_types : [ //只允许上传图片和mp4文件
{ title : "MP4 files", extensions : "flv,mp4" }
],
max_file_size : '500mb', //最大只能上传10mb的文件
prevent_duplicates : true //不允许选取重复文件
},
init: {
PostInit: function() {
document.getElementById('ossfile').innerHTML = '';
document.getElementById('postfiles').onclick = function() {
set_upload_param(uploader, '', false);
return false;
};
},
FilesAdded: function(up, files) {
// plupload.each(files, function(file) {
// document.getElementById('ossfile').innerHTML += '
' + file.name + ' (' + plupload.formatSize(file.size) + ')'
// +'
'
// +'
';
// });
var file=files[files.length-1].getSource().getSource();
var fileBefore=files[files.length-1];
var tol = 0; //获取总时长 秒
var url = createObjectURL(file);
var lock=false;
$("#fileVideo").prop("src", url);
$("#fileVideo")[0].addEventListener("loadedmetadata", function() {
if(lock==false){
tol = this.duration; //获取总时长 秒
//console.log("时长:" + tol);
document.getElementById('ossfile').innerHTML += '
' + fileBefore.name+ ' (time:' + tol +' ,' + plupload.formatSize(fileBefore.size) + ')'
+''
+'
';
$("#videoFileSize").val(fileBefore.size);
$("#videoFileTime").val(tol);
lock=true;
}
});
var param = {};
var inputs =$(".BasicInfo").find("input,select");
if(!business.video.beforeUpload(param,inputs)){
return false;
}

},
BeforeUpload: function(up, file) {
check_object_radio();
set_upload_param(up, file.name, true);
},
UploadProgress: function(up, file) {
var d = document.getElementById(file.id);
d.getElementsByTagName('b')[0].innerHTML = '' + file.percent + "%";
var prog = d.getElementsByTagName('div')[0];
var progBar = prog.getElementsByTagName('div')[0]
progBar.style.width= 2*file.percent+'px';
progBar.setAttribute('aria-valuenow', file.percent);
},
FileUploaded: function(up, file, info) {
if (info.status == 200)
{
//document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '
upload to oss success, object name:' + get_uploaded_object_name(file.name);
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功!';
$("#"+file.id).find(".video_upload_delete").show();
$("#"+file.id).find(".video_upload_cancel").hide();
//TODO 保存到数据库--这边是回调方法
//调用video/upload.js的上传方法
$("#videoFileName").val(host+get_uploaded_object_name(file.name));
console.log("上传路径:"+$("#videoFileName").val());
//上传
business.video.upload();
}
else
{
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
}
},
Error: function(up, err) {
if (err.code == -600) {
document.getElementById('console').appendChild(document.createTextNode("/n选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小"));
}
else if (err.code == -601) {
document.getElementById('console').appendChild(document.createTextNode("/n选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型"));
}
else if (err.code == -602) {
document.getElementById('console').appendChild(document.createTextNode("/n这个文件已经上传过一遍了"));
}
else
{
document.getElementById('console').appendChild(document.createTextNode("/nError xml:" + err.response));
}
}
}
});
uploader.init();

html








您所选择的文件列表:



视频列表   






   




选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小

    
    
    
选择视频




js
https://help.aliyun.com/document_detail/oss/practice/pc_web_upload/js_php_upload.html
需要用到



输入图片说明

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台