com.aliyun.oss.model.PutObjectResult Java Examples

The following examples show how to use com.aliyun.oss.model.PutObjectResult. 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: OssBootUtil.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件到oss
 * @param stream
 * @param relativePath
 * @return
 */
public static String upload(InputStream stream, String relativePath) {
    String FILE_URL = null;
    String fileUrl = relativePath;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
        FILE_URL = staticDomain + "/" + relativePath;
    } else {
        FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
    }
    PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(),stream);
    // 设置权限(公开读)
    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    if (result != null) {
        log.info("------OSS文件上传成功------" + fileUrl);
    }
    return FILE_URL;
}
 
Example #2
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 #3
Source File: TestOSSService.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws OSSException, ClientException, IOException {
    OSSClient client = new OSSClient("oss-cn-hangzhou.aliyuncs.com", "", "", "");
    // BucketInfo info = client.getBucketInfo("edrmry");
    boolean exists = client.doesBucketExist("edrmry");
    System.out.println(exists);
    // System.out.println(client.listBuckets().size());
    // client.createBucket("dzh1");
    PutObjectResult r = client.putObject("edrmry", "dzh1.jpg", new FileInputStream("/Users/dzh/Pictures/8.pic.jpg"));
    System.out.println(r.getETag());
    OSSObject o = client.getObject("edrmry", "dzh1");
    InputStream is = o.getObjectContent();

    FileOutputStream fos = new FileOutputStream("/Users/dzh/Pictures/8.pic.2.jpg");
    int len = 0;
    byte[] buf = new byte[32];
    while ((len = is.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
    fos.flush();
    fos.close();
}
 
Example #4
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 #5
Source File: AliossTemplate.java    From blade-tool with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SneakyThrows
public BladeFile put(String bucketName, InputStream stream, String key, boolean cover) {
	makeBucket(bucketName);
	String originalName = key;
	key = getFileName(key);
	// 覆盖上传
	if (cover) {
		ossClient.putObject(getBucketName(bucketName), key, stream);
	} else {
		PutObjectResult response = ossClient.putObject(getBucketName(bucketName), key, stream);
		int retry = 0;
		int retryCount = 5;
		while (StringUtils.isEmpty(response.getETag()) && retry < retryCount) {
			response = ossClient.putObject(getBucketName(bucketName), key, stream);
			retry++;
		}
	}
	BladeFile file = new BladeFile();
	file.setOriginalName(originalName);
	file.setName(key);
	file.setLink(fileLink(bucketName, key));
	return file;
}
 
Example #6
Source File: AliyunStorage.java    From litemall with MIT License 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

}
 
Example #7
Source File: AliyunStorage.java    From mall with MIT License 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example #8
Source File: OssBootUtil.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(MultipartFile file, String fileDir) {
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.getInputStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            System.out.println("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #9
Source File: OssBootUtil.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件到oss
 * @param stream
 * @param relativePath
 * @return
 */
public static String upload(InputStream stream, String relativePath) {
    String FILE_URL = null;
    String fileUrl = relativePath;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
        FILE_URL = staticDomain + "/" + relativePath;
    } else {
        FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
    }
    PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(),stream);
    // 设置权限(公开读)
    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    if (result != null) {
        log.info("------OSS文件上传成功------" + fileUrl);
    }
    return FILE_URL;
}
 
Example #10
Source File: AliyunStorage.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

}
 
Example #11
Source File: AliyunStorage.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
	try {
		logger.info("阿里云存储OSS对象 内容长度:{},文件类型:{},KeyName:{}",contentLength,contentType,keyName);
		// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentLength(contentLength);
		objectMetadata.setContentType(contentType);
		
		// 对象键(Key)是对象在存储桶中的唯一标识。
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
		
		PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
		if (putObjectResult != null && putObjectResult.getResponse() != null) {
			logger.info("阿里云存储结果code:" + putObjectResult.getResponse().getStatusCode());
		}
	} catch (Exception ex) {
		logger.error("阿里云存储 keyName:{} ,失败:{}",keyName,ex.getMessage());
		ex.printStackTrace();
	}

}
 
Example #12
Source File: AliOSSBlobStore.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public String putBlob(String container, Blob blob) {
    return doOssOperation(oss -> {
        try {
            ObjectMetadata objectMetadata = createObjectMetadataFromBlob(blob);
            PutObjectRequest request = new PutObjectRequest(container, blob.getMetadata()
                                                                           .getProviderId(), blob.getPayload()
                                                                                                 .openStream(), objectMetadata);
            PutObjectResult result = oss.putObject(request);
            return result.getETag();
        } catch (IOException e) {
            throw new SLException(e);
        }
    });
}
 
Example #13
Source File: OSSBootUtil.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(imgDomain)) {
            FILE_URL = imgDomain + "/"  + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }

        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            System.out.println("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #14
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public ObjectOperation store(File file, ObjectMetadata meta, Consumer<PutObjectResult> onCompleted){
	if(!file.exists()){
		throw new BaseException("file is not exists!");
	}
	PutObjectResult result = putObject(new PutObjectRequest(bucketName, key, file, meta));
	if (onCompleted!=null) {
		onCompleted.accept(result);
	} else {
		if (!result.getResponse().isSuccessful()) {
			throw new BaseException("uplaod to oss error: " + result.getResponse().getErrorResponseAsString());
		}
	}
	return this;
}
 
Example #15
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 * @param filePath 上传后的文件所在OSS的目录、路径,如 "jar/file/"
 * @param fileName 上传的文件名,如“xnx3.jar”;主要拿里面的后缀名。也可以直接传入文件的后缀名如“.jar”
 * @param inputStream {@link InputStream}
 * @return {@link PutResult} 若失败,返回null
 */
public static PutResult put(String filePath,String fileName,InputStream inputStream){
	String fileSuffix=com.xnx3.Lang.subString(fileName, ".", null, 3);	//获得文件后缀,以便重命名
       String name=Lang.uuid()+"."+fileSuffix;
       String path = filePath+name;
       PutObjectResult pr = getOSSClient().putObject(bucketName, path, inputStream);
	return new PutResult(name, path,url+path);
}
 
Example #16
Source File: OSSUtils.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 * @param filePath 上传后的文件所在OSS的目录、路径,如 "jar/file/"
 * @param fileName 上传的文件名,如“xnx3.jar”;主要拿里面的后缀名。也可以直接传入文件的后缀名如“.jar”
 * @param inputStream {@link InputStream}
 * @return {@link PutResult} 若失败,返回null
 */
public PutResult put(String filePath,String fileName,InputStream inputStream){
	String fileSuffix=com.xnx3.Lang.subString(fileName, ".", null, 3);	//获得文件后缀,以便重命名
       String name=Lang.uuid()+"."+fileSuffix;
       String path = filePath+name;
       PutObjectResult pr = getOSSClient().putObject(bucketName, path, inputStream);
	return new PutResult(name, path,url+path);
}
 
Example #17
Source File: AliOSSBlobStoreTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutBlob() {
    Mockito.when(ossClient.putObject(any())).thenReturn(new PutObjectResult());
    Blob blob = new BlobBuilderImpl().name(FILENAME)
                                     .payload(PAYLOAD)
                                     .userMetadata(getUserMetadata())
                                     .build();
    aliOSSBlobStore.putBlob(CONTAINER, blob);
    Mockito.verify(ossClient)
           .putObject(any(PutObjectRequest.class));
}
 
Example #18
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 #19
Source File: OssUploadServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public String uploadNetFile(String url) throws IOException, NoSuchAlgorithmException {
    EntityWrapper<Rescource> wrapper = new EntityWrapper<>();
    wrapper.eq("source","oss");
    wrapper.eq("original_net_url",url);
    Rescource rescource = rescourceService.selectOne(wrapper);
    if(rescource != null){
        return rescource.getWebUrl();
    }
    String ossDir = getUploadInfo().getOssDir(),
            fileName = RandomUtil.randomUUID();
    StringBuffer returnUrl = new StringBuffer(getUploadInfo().getOssBasePath());
    StringBuffer key = new StringBuffer();
    if(ossDir != null && !"".equals(ossDir)){
        key.append(ossDir).append("/");
    }
    key.append(fileName).append(".jpg");
    StringBuffer sb = new StringBuffer(fileName);
    InputStream inputStream = new URL(url).openStream();
    PutObjectResult putObjectResult = getOSSClient().putObject(getUploadInfo().getOssBucketName(), key.toString(), inputStream);
    ResponseMessage responseMessage = putObjectResult.getResponse();
    returnUrl.append(key);
    rescource = new Rescource();
    rescource.setFileName(sb.append(".jpg").toString());
    rescource.setHash(putObjectResult.getETag());
    rescource.setWebUrl(returnUrl.toString());
    rescource.setOriginalNetUrl(url);
    rescource.setSource("oss");
    rescource.insert();
    inputStream.close();

    getOSSClient().shutdown();
    return returnUrl.toString();
}
 
Example #20
Source File: OssBootUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param file    待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(MultipartFile file, String fileDir,String customBucket) {
        String FILE_URL = null;
        initOSS(endPoint, accessKeyId, accessKeySecret);
        StringBuilder fileUrl = new StringBuilder();
        String newBucket = bucketName;
        if(oConvertUtils.isNotEmpty(customBucket)){
            newBucket = customBucket;
        }
        try {
            //判断桶是否存在,不存在则创建桶
            if(!ossClient.doesBucketExist(newBucket)){
                ossClient.createBucket(newBucket);
            }
            // 获取文件名
            String orgName = file.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            fileUrl = fileUrl.append(fileDir + fileName);

            if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
                FILE_URL = staticDomain + "/" + fileUrl;
            } else {
                FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
            }
            PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
            // 设置权限(公开读)
//            ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return FILE_URL;
    }
 
Example #21
Source File: OSSBootUtil.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(MultipartFile file, String fileDir) {
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(imgDomain)) {
            FILE_URL = imgDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }

        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.getInputStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            System.out.println("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #22
Source File: OssBootUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #23
Source File: OssBootUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param file    待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(MultipartFile file, String fileDir,String customBucket) {
        String FILE_URL = null;
        initOSS(endPoint, accessKeyId, accessKeySecret);
        StringBuilder fileUrl = new StringBuilder();
        String newBucket = bucketName;
        if(oConvertUtils.isNotEmpty(customBucket)){
            newBucket = customBucket;
        }
        try {
            //判断桶是否存在,不存在则创建桶
            if(!ossClient.doesBucketExist(newBucket)){
                ossClient.createBucket(newBucket);
            }
            // 获取文件名
            String orgName = file.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            fileUrl = fileUrl.append(fileDir + fileName);

            if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
                FILE_URL = staticDomain + "/" + fileUrl;
            } else {
                FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
            }
            PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
            // 设置权限(公开读)
//            ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
            if (result != null) {
                log.info("------OSS文件上传成功------" + fileUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return FILE_URL;
    }
 
Example #24
Source File: OssCossEndpoint.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public OssPutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata) {
	try {
		OssPutObjectResult putObjectRes = new OssPutObjectResult();
		PutObjectResult ossPutObjectRes = ossClient.putObject(bucketName, key, input,
				((OssObjectMetadata) metadata).toAliyunOssObjectMetadata());
		putObjectRes.setETag(ossPutObjectRes.getETag());
		putObjectRes.setVersionId(ossPutObjectRes.getVersionId());
		return putObjectRes;
	} finally {
		IOUtils.closeQuietly(input);
	}
}
 
Example #25
Source File: AliyunUtil.java    From roncoo-education with MIT License 5 votes vote down vote up
/**
 * 文件存储入OSS
 * 
 * @param bucketName
 * @param key
 * @param inputStream
 */
private static PutObjectResult putObjectForFile(String endpoint, String keyId, String keySecret, String bucketName, String key, InputStream inputStream, String fileName) {
	OSSClient ossClient = getOssClient(endpoint, keyId, keySecret);
	ObjectMetadata meta = new ObjectMetadata();
	if (StringUtils.isNotBlank(fileName)) {
		meta.setContentDisposition("attachment;filename={}".replace("{}", fileName));
		meta.setObjectAcl(CannedAccessControlList.Private);
	}
	return ossClient.putObject(bucketName, key, inputStream, meta);
}
 
Example #26
Source File: OssBootUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #27
Source File: OssBootUtil.java    From teaching with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            System.out.println("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
 
Example #28
Source File: OssUploadServiceImpl.java    From mysiteforme with Apache License 2.0 4 votes vote down vote up
@Override
public String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException {
    String fileName =null,realNames = "";
    StringBuffer returnUrl = new StringBuffer(getUploadInfo().getOssBasePath());
    String ossDir = getUploadInfo().getOssDir();
    try {
        fileName = file.getOriginalFilename();
        //上传文件
        StringBuffer realName = new StringBuffer(UUID.randomUUID().toString());
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        realName.append(fileExtension);
        QETag tag = new QETag();
        String hash = tag.calcETag(file);
        Rescource rescource = new Rescource();
        EntityWrapper<RestResponse> wrapper = new EntityWrapper<>();
        wrapper.eq("hash",hash);
        wrapper.eq("source","oss");
        rescource = rescource.selectOne(wrapper);
        if( rescource!= null){
            return rescource.getWebUrl();
        }

        InputStream is = file.getInputStream();

        Long fileSize = file.getSize();
        //创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(is.available());
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentEncoding("utf-8");
        metadata.setContentType(ToolUtil.getContentType(fileName));
        StringBuffer description = new StringBuffer("filename/filesize=");
        description.append(realNames).append("/").append(fileSize).append("Byte.");
        metadata.setContentDisposition(description.toString());

        StringBuffer key = new StringBuffer();
        if(ossDir != null && !"".equals(ossDir)){
            key.append(ossDir).append("/");
            returnUrl.append(ossDir).append("/");
        }
        key.append(realName);
        returnUrl.append(realName);
        PutObjectResult putResult = getOSSClient().putObject(getUploadInfo().getOssBucketName(), key.toString(), is, metadata);
        //解析结果
        System.out.println("md5码为"+putResult.getETag());
        rescource = new Rescource();
        rescource.setFileName(realName.toString());
        rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.getSize()/1024)+"kb");
        rescource.setHash(hash);
        rescource.setFileType(StringUtils.isBlank(fileExtension)?"unknown":fileExtension);
        rescource.setWebUrl(returnUrl.toString());
        rescource.setSource("oss");
        rescource.insert();
        getOSSClient().shutdown();
        is.close();
    } catch (Exception e) {
        throw new MyException("上传阿里云OSS服务器异常." + e.getMessage());
    }
    return returnUrl.toString();
}
 
Example #29
Source File: OssCossEndpoint.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Override
public com.wl4g.devops.coss.model.PutObjectResult putObjectMetaData(String bucketName, String key, ObjectMetadata metadata) {
	//TODO
	return null;
}
 
Example #30
Source File: DemoController.java    From zheng with MIT License 4 votes vote down vote up
@GetMapping("/aliyun/upload1")
public String upload1() {
    PutObjectResult putObjectResult = aliyunOssClient.putObject(OssConstant.ALIYUN_OSS_BUCKET_NAME, "text.txt", new ByteArrayInputStream("Hello OSS".getBytes()));
    return "success";
}