| | |
| | | String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; |
| | | String bucketName = ConstantPropertiesUtils.BUCKET_NAME; |
| | | |
| | | DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| | | |
| | | System.out.println("准备上传--" + dtf2.format(LocalDateTime.now())); |
| | | // 创建OSSClient实例。 |
| | | OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); |
| | | // 上传文件流 |
| | |
| | | LocalDate date = LocalDate.now(); |
| | | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); |
| | | String fileName = "sczf/" + date.format(formatter) + RandomUtils.generateRandomInt(8) + "." + ext; |
| | | System.out.println("文件地址:" + fileName); |
| | | |
| | | ObjectMetadata objectMetadata = new ObjectMetadata(); |
| | | objectMetadata.setContentType(getcontentType(ext)); |
| | | // 调用oss的方法实现长传 |
| | | // 第一个参数 bucketName |
| | | // 第二个参数 上传到oss的文件路径和文件名称 |
| | | ossClient.putObject(bucketName, fileName, inputStream, objectMetadata); |
| | | // 关闭OSSClient。 |
| | | ossClient.shutdown(); |
| | | // 把上传的文件路径返回 (手动拼接) |
| | | // 这里设置图片有效时间 我设置了30年 |
| | | Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); |
| | | String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); |
| | | System.out.println("oss上传成功:" + url); |
| | | |
| | | // URL urlO = new URL(url); |
| | | // HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); |
| | | // conn.setRequestMethod("GET"); |
| | | // conn.setConnectTimeout(10 * 1000); |
| | | // conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); |
| | | // |
| | | // InputStream inputStream2 = conn.getInputStream();// 通过输入流获取图片数据 |
| | | // |
| | | // byte[] data = readInputStream(inputStream2); |
| | | // |
| | | // System.out.println("获取图片成功:" + url); |
| | | System.out.println("开始上传--" + dtf2.format(LocalDateTime.now())); |
| | | |
| | | ossClient.putObject(bucketName, fileName, inputStream, objectMetadata); |
| | | ossClient.shutdown(); |
| | | |
| | | Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); |
| | | |
| | | String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); |
| | | // System.out.println("oss上传成功:" + url); |
| | | |
| | | System.out.println("上传完成--" + dtf2.format(LocalDateTime.now())); |
| | | return url; |
| | | } catch (Exception e) { |
| | | System.out.println("oss异常:" + e.getMessage()); |
| | |
| | | } |
| | | } |
| | | |
| | | |
| | | public static String getcontentType(String FilenameExtension) { |
| | | if (FilenameExtension.equalsIgnoreCase(".mp4")||FilenameExtension.equalsIgnoreCase(".mov")) { |
| | | return "video/mp4"; |