近期项目中需要将前台vue穿过来base64格式的图片记录保存存到阿里云oss上,通过网上找的一些方法结合自己的实际情况终于实现了,下面直接上代码:
前台vue代码:
业务层抵用上传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.out.println("strUrl = [" + strUrl + "]"); return splitUrl(strUrl); } else { System.out.println("key = [" + key + "]"); return splitUrl(key); } } /** * 切割url * * @param url * @return */ public static String splitUrl(String url) { if (url.indexOf("?Expires") != -1) { return url.split("Expires")[0].substring(0,url.split("Expires")[0].length() -1 ); } return url; } //base64字符串转化成图片 public static boolean GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) //图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;ilength;++i) { if(b[i]<0) if(b[i]<0) {//调整异常数据 b[i]+=256; } } //生成jpeg图片 String keys = RandomUtils.getNickName(); String imgFilePath = "/data/sites/duojia369/webapps/duojia/supplier/"+keys+"new.jpg";//新生成的图片 // String imgFilePath = "C:\\Users\\Administrator\\Desktop\\工作安排\\"+keys+"new.jpg"; OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 字符串转图片 * @param base64String */ public static boolean base64StringToImage(String base64String,String toImagePath,String imageType) { try { BASE64Decoder decoder = new sun.misc.BASE64Decoder(); byte[] bytes1 = decoder.decodeBuffer(base64String); ByteArrayInputStream bais = new ByteArrayInputStream(bytes1); RenderedImage bi1 = ImageIO.read(bais); File w2 = new File(toImagePath);// 可以是jpg,png,gif格式 if(!w2.exists()){ w2.createNewFile(); System.out.println("no exist====="); } System.out.println("pass..........."); return ImageIO.write(bi1, imageType, w2);// 不管输出什么格式图片,此处不需改动 } catch (IOException e) { e.printStackTrace(); return false; } } //图片转化成base64字符串 public static String GetImageStr() {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理 String imgFile = "C:\\Users\\Administrator\\Desktop\\工作安排\\q.jpg";//待处理的图片 InputStream in = null; byte[] data = null; //读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } //对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);//返回Base64编码过的字节数组字符串 } //测试 /*public static void main(String[] args) { String imgStr = "iVBORw0KGgoAAAANSUhEUgAAAHoAAACACAYAAADEUH2bAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZ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YQhN0lmiHGBK33+zjcZet8n4PzwmFJ0o2ysRO3rF2QYcarDtG8Igpp/2OOal+vzHdvn/XxKMyzS123/pxtnPZYAHhZwGfGiLNTbiAD33hVuIKAhCZ8KGfw2I8kMFCZU7FnnEWD/grCt5iDq4rjHSdVs5d7pCNFBBOtDrA1CPt65mjVPMnW93WEkYkZueqo9qdKk1j5GHph5fBxT0f8vwAC1C4TfKCbO3wAAAABJRU5ErkJggg=="; GenerateImage(imgStr); // GetImageStr(); }*/ /** * 创建存储空间 * @param ossClient OSS连接 * @param bucketName 存储空间 * @return */ public static String createBucketName(OSSClient ossClient,String bucketName){ //存储空间 final String bucketNames=bucketName; if(!ossClient.doesBucketExist(bucketName)){ //创建存储空间 Bucket bucket=ossClient.createBucket(bucketName); logger.info("创建存储空间成功"); return bucket.getName(); } return bucketNames; } /** * 删除存储空间buckName * @param ossClient oss对象 * @param bucketName 存储空间 */ public static void deleteBucket(OSSClient ossClient, String bucketName){ ossClient.deleteBucket(bucketName); logger.info("删除" + bucketName + "Bucket成功"); } /** * 创建模拟文件夹 * @param ossClient oss连接 * @param bucketName 存储空间 * @param folder 模拟文件夹名如"qj_nanjing/" * @return 文件夹名 */ public static String createFolder(OSSClient ossClient,String bucketName,String folder){ //文件夹名 final String keySuffixWithSlash =folder; //判断文件夹是否存在,不存在则创建 if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){ //创建文件夹 ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0])); logger.info("创建文件夹成功"); //得到文件夹名 OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash); String fileDir=object.getKey(); return fileDir; } return keySuffixWithSlash; } /** * 根据key删除OSS服务器上的文件 * @param ossClient oss连接 * @param bucketName 存储空间 * @param folder 模拟文件夹名 如"qj_nanjing/" * @param key Bucket下的文件的路径名+文件名 如:"upload/cake.jpg" */ public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key){ ossClient.deleteObject(bucketName, folder + key); logger.info("删除" + bucketName + "下的文件" + folder + key + "成功"); } /** * 上传图片至OSS * @param * @param file 上传文件(文件全路径如:D:\\image\\cake.jpg) * @return String 返回的唯一MD5数字签名 * */ public static String uploadObject2OSS(File file) { OSSClient ossClient = OSSFileUpload.getOSSClient(); String resultStr = null; try { //以输入流的形式上传文件 InputStream is = new FileInputStream(file); //文件名 String fileName = file.getName(); //文件大小 Long fileSize = file.length(); //创建上传Object的Metadata ObjectMetadata metadata = new ObjectMetadata(); //上传的文件的长度 metadata.setContentLength(is.available()); //指定该Object被下载时的网页的缓存行为 metadata.setCacheControl("no-cache"); //指定该Object下设置Header metadata.setHeader("Pragma", "no-cache"); //指定该Object被下载时的内容编码格式 metadata.setContentEncoding("utf-8"); //文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成, //如果没有扩展名则填默认值application/octet-stream metadata.setContentType(getContentType(fileName)); //指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称) metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte."); //上传文件 (上传文件流的形式) PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, is, metadata); //解析结果 resultStr = putResult.getETag(); } catch (Exception e) { e.printStackTrace(); logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e); } return resultStr; } /** * 通过文件名判断并获取OSS服务文件上传时文件的contentType * @param fileName 文件名 * @return 文件的contentType */ public static String getContentType(String fileName){ //文件的后缀名 String fileExtension = fileName.substring(fileName.lastIndexOf(".")); if(".bmp".equalsIgnoreCase(fileExtension)) { return "image/bmp"; } if(".gif".equalsIgnoreCase(fileExtension)) { return "image/gif"; } if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension) ) { return "image/jpeg"; } if(".html".equalsIgnoreCase(fileExtension)) { return "text/html"; } if(".txt".equalsIgnoreCase(fileExtension)) { return "text/plain"; } if(".vsd".equalsIgnoreCase(fileExtension)) { return "application/vnd.visio"; } if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) { return "application/vnd.ms-powerpoint"; } if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) { return "application/msword"; } if(".xml".equalsIgnoreCase(fileExtension)) { return "text/xml"; } //默认返回类型 return "image/jpeg"; } // public OSSFileUpload() { // ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // } // public static void main(String[] args) throws Exception { // //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 = "https://oss-cn-beijing.aliyuncs.com"; // // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号 // private static String accessKeyId = "LTAIwSYt7T0g4Zp3"; // private static String accessKeySecret = "vIZ2xV4ZVwZ9Ij43NkO3rjiKlcGAOu"; // private static String bucketName = "img-video"; //需要存储的bucketName // private static String filedir = "supplier/ "; //图片保存路径 // // /** // * 获取阿里云OSS客户端对象 // * @return ossClient // */ // public static OSSClient getOSSClient(){ // return new OSSClient(endpoint,accessKeyId,accessKeySecret); // } // // /** // * 创建存储空间 // * @param ossClient OSS连接 // * @param bucketName 存储空间 // * @return // */ // public static String createBucketName(OSSClient ossClient,String bucketName){ // //存储空间 // final String bucketNames=bucketName; // if(!ossClient.doesBucketExist(bucketName)){ // //创建存储空间 // Bucket bucket=ossClient.createBucket(bucketName); // logger.info("创建存储空间成功"); // return bucket.getName(); // } // return bucketNames; // } // // /** // * 删除存储空间buckName // * @param ossClient oss对象 // * @param bucketName 存储空间 // */ // public static void deleteBucket(OSSClient ossClient, String bucketName){ // ossClient.deleteBucket(bucketName); // logger.info("删除" + bucketName + "Bucket成功"); // } // // /** // * 创建模拟文件夹 // * @param ossClient oss连接 // * @param bucketName 存储空间 // * @param folder 模拟文件夹名如"qj_nanjing/" // * @return 文件夹名 // */ // public static String createFolder(OSSClient ossClient,String bucketName,String folder){ // //文件夹名 // final String keySuffixWithSlash =folder; // //判断文件夹是否存在,不存在则创建 // if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){ // //创建文件夹 // ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0])); // logger.info("创建文件夹成功"); // //得到文件夹名 // OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash); // String fileDir=object.getKey(); // return fileDir; // } // return null; // } // // // /** // * Description: 判断OSS服务文件上传时文件的contentType // * // * @param FilenameExtension 文件后缀 // * @return String // */ // public static String getcontentType(String FilenameExtension) { // if (FilenameExtension.equalsIgnoreCase(".bmp")) { // return "image/bmp"; // } // if (FilenameExtension.equalsIgnoreCase(".gif")) { // return "image/gif"; // } // if (FilenameExtension.equalsIgnoreCase(".jpeg") || // FilenameExtension.equalsIgnoreCase(".jpg") || // FilenameExtension.equalsIgnoreCase(".png")) { // return "image/jpeg"; // } // if (FilenameExtension.equalsIgnoreCase(".html")) { // return "text/html"; // } // if (FilenameExtension.equalsIgnoreCase(".txt")) { // return "text/plain"; // } // if (FilenameExtension.equalsIgnoreCase(".vsd")) { // return "application/vnd.visio"; // } // if (FilenameExtension.equalsIgnoreCase(".pptx") || // FilenameExtension.equalsIgnoreCase(".ppt")) { // return "application/vnd.ms-powerpoint"; // } // if (FilenameExtension.equalsIgnoreCase(".docx") || // FilenameExtension.equalsIgnoreCase(".doc")) { // return "application/msword"; // } // if (FilenameExtension.equalsIgnoreCase(".xml")) { // return "text/xml"; // } // return "image/jpeg"; // } // // /** // * 获得url链接 // * // * @param key // * @return // */ // public String getUrl(String key) { // // 设置URL过期时间为10年 3600l* 1000*24*365*10 // Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10); // // 生成URL // URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); // if (url != null) { // return url.toString(); // } // return null; // } }