vue 傳base64到後臺後臺傳到oss的java實現
阿新 • • 發佈:2018-12-30
近期專案中需要將前臺vue穿過來base64格式的圖片記錄儲存存到阿里雲oss上,通過網上找的一些方法結合自己的實際情況終於實現了,下面直接上程式碼:
前臺vue程式碼:
<template> <div class="insti-container"> <div v-if="mediciner"> <h2>營業執照</h2> <div class="loadImg"> <div id="img-group"> <this.imports() 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', init: { PostInit: function() { document.getElementById('ossfile').innerHTML = ''; // document.getElementById('postfiles').onclick = function() { // set_upload_param(uploader, '', false); // return false; // }; },
FilesAdded: function(up, files) { //console.log(up.total);return; if(up.total.queued == 2){ return; } plupload.each(files, function(file) { document.getElementById('ossfile').innerHTML = '<div id="' + file.id + '"><b></b>' //document.getElementById('ossfile').innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>' //+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' //+'<div class="progress"></div>' +'</div>'; }); up.start(); },
BeforeUpload: function(up, file) { check_object_radio(); get_dirname(); set_upload_param(up, file.name, true); },
UploadProgress: function(up, file) { var d = document.getElementById(file.id); //d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>"; //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) { $(".img-item").show(); $(".Single").css({ "position": "absolute", "top": 0, "opacity": 0 }) //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name); imgUrl = host + '/' + get_uploaded_object_name(file.name); document.getElementById('seeimg').setAttribute('src',imgUrl); this.imgUrl = imgUrl; }else{ document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response; } }, Error: function(up, err) { document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response)); } } });
uploader.init(); }}</script><!-- Add "scoped" attribute to limit CSS to this component only --><style scoped lang="less">@import "../less/functions";.insti-container{ width: 95%; height: 100%; background: #1d1d28; overflow-y: auto; overflow-x: hidden; margin: 0 auto; h2{ font-weight: normal; color: #fff; font-size: 16px; padding: .5rem 0; } .Submission{ width: 75%; background-image: linear-gradient(-135deg, #2CBB86 0%, #2CBB55 100%); border-radius: 50px; padding: .2rem 0; margin: 1rem auto 0; display: block; color: #fff; font-size: 16px; } .Prompt{ width: 75%; color: #999; font-size: 12px; margin: .5rem auto; } #img-group{ width: 95%; height: auto; display: -webkit-flex; flex-wrap: wrap; justify-content: flex-start; margin: 0 auto; .img-item { width: 30%; height: 2rem; position: relative; margin: .2rem .15rem; position: relative; border-radius: 5px; overflow: hidden; .closeImg{ width: .5rem; height: .5rem; position: absolute; right: 0; top: 0; background:url(../images/addInfo/deleteImg.png) no-repeat center; background-size: contain } } } .img-item img { width: 100%; height: auto; } .add-pic { background: url(../images/addInfo/addImg.png) no-repeat center; background-size: contain; width: 30%; height: 2rem; text-align: center; font-size: 2rem; line-height: 3.5rem; color: #979797; position: relative; overflow: hidden; a{ display: block; width: 100%; height: 100%; } }
.add-pic input { opacity: 0; }}.insti-container::-webkit-scrollbar { display: none; }.loadImg{ position: relative;}</style>
業務層抵用上傳oss工具類
String[] src = orgImgUrl.split(","); SerialBlob serialBlob = OSSFileUpload.decodeToImage(src[1]); InputStream binaryStream = serialBlob.getBinaryStream(); String keys = RandomUtils.getNickName()+".jpg"; String url = OSSFileUpload.uploadFile2OSS(binaryStream, keys); System.out.println("userAddVO2 = " + url+"===========================================================");
後臺上傳oss工具類:
package com.duojia.eagle.utils; import com.alibaba.druid.util.StringUtils; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.Bucket; import com.aliyun.oss.model.OSSObject; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.imageio.ImageIO; import javax.sql.rowset.serial.SerialBlob; import java.awt.image.RenderedImage; import java.io.*; import java.net.URL; import java.util.Date; import java.util.Random;; public class OSSFileUpload { private static final Logger logger = LoggerFactory.getLogger(OSSFileUpload.class); // endpoint以杭州為例,其它region請按實際情況填寫 private static String endpoint = "阿里雲查詢"; // 阿里雲主賬號AccessKey擁有所有API的訪問許可權,風險很高。強烈建議您建立並使用RAM賬號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM賬號 private static String accessKeyId = "阿里雲查詢"; private static String accessKeySecret = "阿里雲查詢"; private static String bucketName = "img-video"; //需要儲存的bucketName private static String filedir = "supplier/ "; //圖片儲存路徑\ private static String clientdir = "clientImg/ "; //圖片儲存路徑 /** * 獲取阿里雲OSS客戶端物件 * @return ossClient */ public static OSSClient getOSSClient(){ return new OSSClient(endpoint,accessKeyId,accessKeySecret); } public static SerialBlob decodeToImage(String imageString) throws Exception { BASE64Decoder decoder = new BASE64Decoder(); byte[] imageByte = decoder.decodeBuffer(imageString); return new SerialBlob(imageByte); } /** * 上傳到OSS伺服器 如果同名檔案會覆蓋伺服器上的 * * @param instream 檔案流 * @param fileName 檔名稱 包括字尾名 * @return 出錯返回"" ,唯一MD5數字簽名 */ public static String uploadFile2OSS(InputStream instream, String fileName) throws Exception{ OSSClient ossClient = OSSFileUpload.getOSSClient(); String ret = ""; try { //建立上傳Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); //上傳檔案 PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = String.valueOf(getUrl(fileName)); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * 上傳到OSS伺服器 如果同名檔案會覆蓋伺服器上的 * * @param instream 檔案流 * @param fileName 檔名稱 包括字尾名 * @return 出錯返回"" ,唯一MD5數字簽名 */ public static String uploadClietImg2OSS(InputStream instream, String fileName) throws Exception{ OSSClient ossClient = OSSFileUpload.getOSSClient(); String ret = ""; try { //建立上傳Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); //上傳檔案 PutObjectResult putResult = ossClient.putObject(bucketName, clientdir + fileName, instream, objectMetadata); ret = String.valueOf(getUrl(fileName)); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * 位元組陣列上傳 * * @Title uploadPic * @param @param * content * @param @param * keys * @param @return * @return String * @Explain */ public static String uploadPic(byte[] content, String keys) { OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 連線oss雲端儲存伺服器 ossClient.putObject(bucketName, keys, new ByteArrayInputStream(content)); String url = String.valueOf(getUrl(keys)); ossClient.shutdown(); return url; } /** * 獲取檔案URL * * @Title getUrl * @param @param * key * @param @return * @return URL */ public static String getUrl(String key) { if (key.indexOf("http") == -1) { OSSClient server = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 連線oss雲端儲存伺服器 // 設定URL過期時間為10年 3600l* 1000*24*365*10 Date expirations = new Date(new Date().getTime() + 1000 * 60 * 5);// url超時時間 // 生成URL URL url = server.generatePresignedUrl(bucketName,filedir + key, expirations); String strUrl = String.valueOf(url); // 關閉client server.shutdown(); System.ou