Java Code Examples for com.aliyun.oss.OSSClient#shutdown()

The following examples show how to use com.aliyun.oss.OSSClient#shutdown() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AliyunOSSTest.java    From mblog with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    // Endpoint以杭州为例,其它Region请按实际情况填写。
    String endpoint = "oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
    String accessKeyId = "";
    String accessKeySecret = "";
    String bucketName = "mtons";

    File file = new File("F:/data/a_2.jpg");
    byte[] bytes = ImageUtils.screenshot(file, 360, 200);
    String key = UpYunUtils.md5(bytes);

    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
    PutObjectResult result = ossClient.putObject(bucketName, "static/"+key + ".jpg", new ByteArrayInputStream(bytes));

    // 关闭OSSClient。
    ossClient.shutdown();
}
 
Example 2
Source File: OSSUploadTest.java    From cms with Apache License 2.0 6 votes vote down vote up
@Test
	public void upload(){
		OSSClient client=OSSClientFactory.create();
		
		String bucketName="b-cdn";
		String path="/opt/001.jpg";
		PutObjectResult result=client.putObject(bucketName, "cms"+path, new File(path));
		JSONObject json = JSONObject.fromObject(result);
		
		System.out.println(json.toString());
		
		// 列举bucket
//		List<Bucket> buckets = client.listBuckets();
//		for (Bucket bucket : buckets) {
//		    System.out.println(" - " + bucket.getName());
//		}
		
		
		client.shutdown();
	}
 
Example 3
Source File: AliOssStorage.java    From springboot-learn with MIT License 6 votes vote down vote up
public void delete() {
    if (StringUtils.isAnyBlank(accessKeyId, accessKeySecret, endpoint, bucketName)) {
        throw new IllegalArgumentException("请先设置配置信息");
    }

    //文件所在的目录名
    String fileDir = "image/jpg/";
    //文件名
    String key = "aliU.png";
    String path = fileDir + key;

    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    // 删除文件。
    ossClient.deleteObject(bucketName, path);

    // 关闭OSSClient。
    ossClient.shutdown();
}
 
Example 4
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String inputStreamUpload(InputStream inputStream, String key, MultipartFile file) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.putObject(os.getBucket(), key, inputStream);
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
}
 
Example 5
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 删除一个OSS中的文件
 * @param objectName
 */
public static void delete(String objectName){
    boolean ossDelEnable = JPressOptions.getAsBool(KEY_OSS_DEL);
    if (ossDelEnable){
        OSSClient ossClient = createOSSClient();
        try {
            ossClient.deleteObject(JPressOptions.get(KEY_BUCKETNAME), objectName);
        }catch (Exception e){

        }finally {
            ossClient.shutdown();
        }
    }
}
 
Example 6
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 同步 阿里云OSS 到本地
 *
 * @param path
 * @param toFile
 * @return
 */
public static boolean download(String path, File toFile) {
    boolean enable = JPressOptions.getAsBool(KEY_ENABLE);

    if (!enable || StrUtil.isBlank(path)) {
        return false;
    }

    path = removeFileSeparator(path);
    String ossBucketName = JPressOptions.get(KEY_BUCKETNAME);
    OSSClient ossClient = createOSSClient();
    try {

        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }

        if (!toFile.exists()) {
            toFile.createNewFile();
        }
        ossClient.getObject(new GetObjectRequest(ossBucketName, path), toFile);
        return true;
    } catch (Throwable e) {
        log.error("aliyun oss download error!!!  path:" + path + "   toFile:" + toFile, e);
        if (toFile.exists()) {
            toFile.delete();
        }
        return false;
    } finally {
        ossClient.shutdown();
    }
}
 
Example 7
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 同步本地文件到阿里云OSS
 *
 * @param path
 * @param file
 * @return
 */
public static boolean uploadsync(String path, File file) {

    boolean enable = JPressOptions.getAsBool(KEY_ENABLE);

    if (!enable || StrUtil.isBlank(path)) {
        return false;
    }

    path = removeFileSeparator(path);
    path = path.replace('\\', '/');

    String ossBucketName = JPressOptions.get(KEY_BUCKETNAME);
    OSSClient ossClient = createOSSClient();

    try {
        ossClient.putObject(ossBucketName, path, file);
        boolean success = ossClient.doesObjectExist(ossBucketName, path);
        if (!success) {
            LogKit.error("aliyun oss upload error! path:" + path + "\nfile:" + file);
        }
        return success;

    } catch (Throwable e) {
        log.error("aliyun oss upload error!!!", e);
        return false;
    } finally {
        ossClient.shutdown();
    }
}
 
Example 8
Source File: OssUploadServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
    ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
    try {
        OSSClient ossClient = new OSSClient(uploadInfo.getOssEndpoint(),uploadInfo.getOssKeyId(), uploadInfo.getOssKeySecret());
        InputStream inputStream = classPathResource .getInputStream();
        ossClient.putObject(uploadInfo.getOssBucketName(), "test.jpg", inputStream, null);
        ossClient.shutdown();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 9
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static void close(OSSClient ossClient) {
    if (ossClient != null) {
        try {
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
 
Example 10
Source File: AliOssStorage.java    From springboot-learn with MIT License 5 votes vote down vote up
public void upload() {

        if (StringUtils.isAnyBlank(accessKeyId, accessKeySecret, endpoint, bucketName)) {
            throw new IllegalArgumentException("请先设置配置信息");
        }

        //文件所在的目录名
        String fileDir = "link/";
        //文件名
        String key = "aliU.png";
        String path = fileDir + key;
        File file = null;
        try {
            //此处的static前不能加/!!!
            file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/images/user.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, path, file);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("访问路径=====》" + endpoint + "/" + path);

    }
 
Example 11
Source File: ImgServiceImpl.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
public void delectOSS(Keys key, String fileName) {
    String endpoint = key.getEndpoint();
    String accessKeyId = key.getAccessKey();
    String accessKeySecret = key.getAccessSecret();
    String bucketName = key.getBucketname();
    String objectName = fileName;
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    ossClient.deleteObject(bucketName, objectName);
    ossClient.shutdown();
}
 
Example 12
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteFile(String key) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.deleteObject(os.getBucket(), key);
    ossClient.shutdown();
}
 
Example 13
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String copyFile(String fromKey, String toKey) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.copyObject(os.getBucket(), fromKey, os.getBucket(), toKey);
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
}
 
Example 14
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String pathUpload(String filePath, String key) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.putObject(os.getBucket(), key, new File(filePath));
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
}
 
Example 15
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传图片到阿里云OSS
 *
 * @param request
 * @param response
 * @param file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "upload/oss/image", method = RequestMethod.POST)
@ResponseBody
public MessageResult uploadOssImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/").toString());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    Assert.isTrue(ServletFileUpload.isMultipartContent(request), sourceService.getMessage("FORM_FORMAT_ERROR"));
    Assert.isTrue(file != null, sourceService.getMessage("NOT_FIND_FILE"));
    log.info("该文件的文件流为转为类型>>>>>>>>>>>"+UploadFileUtil.getFileHeader(file.getInputStream()));
    String fileType=UploadFileUtil.getFileType(file.getInputStream());
    System.out.println("fileType="+fileType);
    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("suffix="+suffix);
        if (!allowedFormat.contains(suffix.trim().toLowerCase())) {
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        if(fileType==null||!allowedFormat.contains(fileType.trim().toLowerCase())){
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        //压缩文件
        String path = request.getSession().getServletContext().getRealPath("/") + "upload/"+file.getOriginalFilename();
        File tempFile=new File(path);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        log.info("=================压缩前"+tempFile.length());
        UploadFileUtil.zipWidthHeightImageFile(tempFile,tempFile,425,638,0.7f);
        log.info("=================压缩后"+tempFile.length());
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        log.info(">>>>>>>>>>上传成功>>>>>>>>>>>>>");
        MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
        mr.setData(uri);
        return mr;
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage());
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("SYSTEM_ERROR"));
    } finally {
        ossClient.shutdown();
    }
}
 
Example 16
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example 17
Source File: SimpleGetObjectSample.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    /*
     * Constructs a client instance with your account for accessing OSS
     */
    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    
    try {
        
        /**
         * Note that there are two ways of uploading an object to your bucket, the one 
         * by specifying an input stream as content source, the other by specifying a file.
         */
        
        /*
         * Upload an object to your bucket from an input stream
         */
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));
        
        /*
         * Upload an object to your bucket from a file
         */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
        
        /*
         * Download an object from your bucket
         */
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
        
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message: " + oe.getErrorCode());
        System.out.println("Error Code:       " + oe.getErrorCode());
        System.out.println("Request ID:      " + oe.getRequestId());
        System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ce.getMessage());
    } finally {
        /*
         * Do not forget to shut down the client finally to release all allocated resources.
         */
        client.shutdown();
    }
}
 
Example 18
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example 19
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传图片到阿里云OSS
 *
 * @param request
 * @param response
 * @param file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "upload/oss/image", method = RequestMethod.POST)
@ResponseBody
public MessageResult uploadOssImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/").toString());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    Assert.isTrue(ServletFileUpload.isMultipartContent(request), sourceService.getMessage("FORM_FORMAT_ERROR"));
    Assert.isTrue(file != null, sourceService.getMessage("NOT_FIND_FILE"));
    log.info("该文件的文件流为转为类型>>>>>>>>>>>"+UploadFileUtil.getFileHeader(file.getInputStream()));
    String fileType=UploadFileUtil.getFileType(file.getInputStream());
    System.out.println("fileType="+fileType);
    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("suffix="+suffix);
        if (!allowedFormat.contains(suffix.trim().toLowerCase())) {
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        if(fileType==null||!allowedFormat.contains(fileType.trim().toLowerCase())){
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        //压缩文件
        String path = request.getSession().getServletContext().getRealPath("/") + "upload/"+file.getOriginalFilename();
        File tempFile=new File(path);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        log.info("=================压缩前"+tempFile.length());
        UploadFileUtil.zipWidthHeightImageFile(tempFile,tempFile,425,638,0.7f);
        log.info("=================压缩后"+tempFile.length());
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        log.info(">>>>>>>>>>上传成功>>>>>>>>>>>>>");
        MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
        mr.setData(uri);
        return mr;
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage());
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("SYSTEM_ERROR"));
    } finally {
        ossClient.shutdown();
    }
}
 
Example 20
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 2 votes vote down vote up
/**
 * close given oss client instance
 *
 * @param ossClient {@link OSSClient}
 * @throws ApiBootObjectStorageException 对象存储异常对象
 */
protected void closeOssClient(OSSClient ossClient) throws ApiBootObjectStorageException {
    ossClient.shutdown();
}