Java实现阿里云oss文预览上传和下载
第一步:引入maven依赖
1 2 3 4 5 6 7 8 9 10 | <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <!--阿里云oss--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version> 2.8 . 2 </version> </dependency> |
第二步:阿里云oss工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; /** * 阿里云 OSS文件类 */ public class AliOssCloudUtil { Log log = LogFactory.getLog(AliOssCloudUtil. class ); /** * 用户的存储空间所在数据中心的访问域名 */ private String endpoint = "oss-cn-hangzhou.aliyuncs.com" ; /** * OSS签名key */ private String accessKeyId = "LTAI5tSJSDtUaXXXX" ; /** * OSS签名密钥 */ private static final String accessKeySecret = "AQLmguaT1BFsOi5oe07iMUXXXXX" ; /** * 存储空间名称 */ private static final String bucketName = "oss-uav-oss" ; //文件存储目录 private String filedir = "uav/" ; private OSSClient ossClient; public AliOssCloudUtil() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } public String getFiledir() { return this .filedir; } //自定义上传文件夹 public AliOssCloudUtil(String filedir) { this .filedir = filedir; ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * 初始化 */ public void init() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * 销毁 */ public void destory() { ossClient.shutdown(); } /** * 上传到OSS服务器 * * @param instream 文件流 * @param fileName 文件名称 包括后缀名 * @return 出错返回"" ,唯一MD5数字签名 */ public String uploadFile2OSS(InputStream instream, String fileName) { String ret = "" ; // 判断bucket是否已经存在,不存在进行创建 if (!doesBucketExist()) { createBucket(); } 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); // 指定上传文件操作时是否覆盖同名Object。 // 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。 // 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。 // 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。 objectMetadata.setHeader( "x-oss-forbid-overwrite" , "false" ); String objectName = filedir + fileName; //上传文件 ossClient.putObject(bucketName, objectName, instream, objectMetadata); // 封装 url 路径 String url = "https://" + bucketName + "." + endpoint + "/" + objectName; ret = url; } catch (IOException e) { log.error(e.getMessage(), e); } finally { ossClient.shutdown(); try { if (instream != null ) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS, * 如果为true则忽略302重定向或镜像;如果为false,则考虑302重定向或镜像。 * yourObjectName 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。 * * @return 存在返回true */ public boolean doesObjectExist(String objectName) { boolean exists = ossClient.doesObjectExist(bucketName, filedir + objectName); return exists; } /** * 判断Bucket是否存在 * * @return 存在返回true */ public boolean doesBucketExist() { boolean exists = ossClient.doesBucketExist(bucketName); return exists; } /** * 创建Bucket */ public void createBucket() { CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); // 设置bucket权限为公共读,默认是私有读写 createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead); // 设置bucket存储类型为低频访问类型,默认是标准类型 createBucketRequest.setStorageClass(StorageClass.IA); boolean exists = ossClient.doesBucketExist(bucketName); if (!exists) { try { ossClient.createBucket(createBucketRequest); // 关闭client ossClient.shutdown(); } catch (Exception e) { log.error(e.getMessage()); } } } /** * Description: 判断OSS服务文件上传时文件的contentType * * @param FilenameExtension 文件后缀 * @return String */ public static String getcontentType(String FilenameExtension) { if ( ".bmp" .equalsIgnoreCase(FilenameExtension)) { return "image/bmp" ; } if ( ".gif" .equalsIgnoreCase(FilenameExtension)) { return "image/gif" ; } if ( ".jpeg" .equalsIgnoreCase(FilenameExtension) || ".jpg" .equalsIgnoreCase(FilenameExtension) || ".png" .equalsIgnoreCase(FilenameExtension)) { return "image/jpg" ; } if ( ".html" .equalsIgnoreCase(FilenameExtension)) { return "text/html" ; } if ( ".txt" .equalsIgnoreCase(FilenameExtension)) { return "text/plain" ; } if ( ".vsd" .equalsIgnoreCase(FilenameExtension)) { return "application/vnd.visio" ; } if ( ".ppt" .equalsIgnoreCase(FilenameExtension) || "pptx" .equalsIgnoreCase(FilenameExtension)) { return "application/vnd.ms-powerpoint" ; } if ( ".doc" .equalsIgnoreCase(FilenameExtension) || "docx" .equalsIgnoreCase(FilenameExtension)) { return "application/msword" ; } if ( ".xml" .equalsIgnoreCase(FilenameExtension)) { return "text/xml" ; } if ( ".mp4" .equalsIgnoreCase(FilenameExtension)) { return "video/mp4" ; } if ( ".mp3" .equalsIgnoreCase(FilenameExtension)) { return "audio/mp3" ; } return "text/html" ; } /** * @Description: 根据文件路径获取InputStream流 */ public InputStream getInputStreamByFileUrl(String fileName) { // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。 OSSObject ossObject = ossClient.getObject(bucketName, fileName); return ossObject.getObjectContent(); } } |
第三步:上传下载文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | public class FlightFileController { @ResponseBody @PostMapping ( "/upload" ) public Response upload( @RequestParam ( "file" ) MultipartFile file) { String filename = file.getResource().getFilename(); //文件名 String pattern = "yyyy-MM-dd" ; String dir = DateFormatUtils.format( new Date(), pattern); String name = "" ; if (getFileType(filename) == 0 ) { name = OssBucketEnum.VIDEO.getValue() + "/" + dir + "/" + filename; } else { name = OssBucketEnum.PICTURE.getValue() + "/" + dir + "/" + filename; } InputStream inputStream = null ; try { inputStream = file.getInputStream(); } catch (IOException e) { e.printStackTrace(); log.info( "上传失败" ); } AliOssCloudUtil util = new AliOssCloudUtil(); //上传成功返回可直接查看文件的url String url = util.uploadFile2OSS(inputStream, name); return Response.success(url); } public int getFileType(String fileName) { int i = 0 ; FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(fileName); //下面是进一判断是视频和图片的区别 if (contentTypeFor != null ) { // 当为图片时不为空,是视频时为空 i = 1 ; } return i; } @PostMapping ( "/downLoad" ) public void downloadFile(String fileName, HttpServletResponse response) { try { AliOssCloudUtil ossClientUtil = new AliOssCloudUtil(); InputStream is = ossClientUtil.getInputStreamByFileUrl(ossClientUtil.getFiledir() + fileName); // 配置文件下载 response.setHeader( "content-type" , "application/octet-stream" ); response.setContentType( "application/octet-stream" ); // 下载文件能正常显示中文 response.setHeader( "Content-Disposition" , "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8" )); OutputStream os = response.getOutputStream(); byte [] b = new byte [ 1024 ]; int len = - 1 ; while ((len = is.read(b)) != - 1 ) { os.write(b, 0 , len); } is.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } } |
now ,fight for future
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程