javaScript 上傳圖片(oss阿里雲)
最近專案有這個這塊的需求,簡單的記錄一下使用過程,以便以後學習、使用。
直接上乾貨分享:
思路:前端js獲取 oss上傳圖片的url地址,將url以json陣列形式傳入後臺,後臺json解析將資料存入資料庫(這裡用的是fastjson)
使用步驟:
1、前端頁面有圖片上傳的圖示,並且增加圖片上傳的input隱藏域,便於拿到上傳的圖片資訊
<div class="middle_div3">
<img src="../img/iconn01.png" id="upload_img" class="img_2" />
<span id="num">0/3</span>
</div>
<input type="hidden" name="fold" value="photo" style="display: none;">
<input type="file" size="30" class="file-img" name='file' id="ossfile" capture="camera" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" style="display: none;">
<span id="progress-bar" style="display: none;"></span>
2、引入阿里雲官方提供的javaScript庫,在js中配置自己的阿里雲賬號等一些資訊
<script type="text/javascript" src="http://gosspublic.alicdn.com/aliyun-oss-sdk.min.js "></script>
<script type="text/javascript" src="../js/oss.js"></script>
3、獲取上傳圖片的url,控制圖片為3個
// oss圖片上傳
//判斷安卓還是ios
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android終端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端
$(".img_2").click(function() {
if(isiOS) {
$('#ossfile').removeAttr("capture");
$("#ossfile").click();
}
$("#ossfile").click();
})
//獲取上傳圖片的url
var img_list = []; //圖片url地址陣列
var num = 0;
function outDone(f_url) { //輸出url
var content = '<img src="' + f_url + '" class="img_2"/>'
$('.middle_div3 img:last').before(content);
img_list.push({"file_value": f_url}); //將json格式的資料存入陣列
num++;
$("#num").html(num + '/3');
if(img_list.length == 3) {
$("#upload_img").hide();
}
return f_url;
}
4、將url陣列轉換為json字串陣列,傳入controller介面中,做業務邏輯,存入資料庫,便於記錄查詢
var json_body = JSON.stringify(img_list);
$.ajax({
type: "post",
url: "http://localhost/estuary-busi/index/submit_xwzl_info.do",
async: true,
data: {
user_id: user_id,
title: title,
type_name: type_name,
content: content,
json_body: json_body,
community_id: community_id
},
dataType: "json",
success: function(result) {
msg("釋出成功");
window.location.reload();
},
error: function() {
console.log("獲取失敗");
}
});
ps: oss.js 相關內容
'use strict';
var appServer = 'http://47.96.71.3:7103/index2/getSt.do';
var bucket = 'kyky';
var region = 'oss-cn-beiji';
var domain = 'http://kyyy.oss-cn-beijin.aliyuncs.cm';
var urllib = OSS.urllib;
var Buffer = OSS.Buffer;
var OSS = OSS.Wrapper;
document.getElementById('ossfile').onchange = function() {
applyTokenDo(uploadFile);
}
var applyTokenDo = function (func) {
var url =appServer;
return urllib.request(url, {
method: 'GET'
}).then(function (result) {
var creds = JSON.parse(result.data).result_info;
var client = new OSS({
region: region,
accessKeyId: creds.AccessKeyId,
accessKeySecret: creds.AccessKeySecret,
stsToken: creds.SecurityToken,
bucket: bucket
});
return func(client);
});
};
var progress = function (p) {
return function (done) {
var bar = document.getElementById('progress-bar');
bar.style.width = Math.floor(p * 100) + '%';
bar.innerHTML = Math.floor(p * 100) + '%';
done();
}
};
var uploadFile = function (client) {
var file = document.getElementById('ossfile').files[0];
if(file==null){
return;
}
var timestamp=new Date().getTime();
var key = "product/"+timestamp+"."+file.name.split(".")[1];
//console.log(file.name + ' => ' + key);
return client.multipartUpload(key, file, {
progress: progress
}).then(function (res) {
var fileUrl="";
if(res.url!=null){
fileUrl=res.url;
}else{
fileUrl=domain+"/"+res.name;
}
//console.log(fileUrl);
outDone(fileUrl); //獲取圖片上傳的url地址
//console.log('upload success: %j', res);
return null;
});
};
java:controller相關程式碼
/**
* 意見反饋
*
* @param user_id
* 使用者編碼
* @param title
* 標題
* @param type_name
* 型別名稱
* @param content
* 內容
* @param json_body
* 圖片資料(Json字串陣列)
* @param community_id
* 小區編碼
* @return map
*/
@RequestMapping(value = "submit_yjfk_info")
@ResponseBody
public Map<String, Object> submit_yjfk_info(String user_id, String title, String type_name, String content,
String community_id, String json_body) {
if (StringUtils.isBlank(user_id)) {
throw new BusinessException("賬戶異常");
}
Map<String, Object> map = new HashMap<String, Object>();
String deal_id = dealInfoService.saveDealInfo(user_id, title, type_name, content, community_id);
List<UserInfoAtt> arrlist = JSON.parseArray(json_body, UserInfoAtt.class);
if (!CollectionUtils.isEmpty(arrlist)) {
for (UserInfoAtt att : arrlist) {
userInfoAttService.saveUserInfoAtt(user_id, "意見反饋圖片", att.getFile_value(), 3, deal_id);
}
}
map.put("deal_id", deal_id);
return map;
}