OSS文件上传下载获取url的代码;

关于阿里OSS文件上传下载的代码如下:

package com.zxq.iov.cloud.sp.fota.utils.common;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;


public class OssDownload {

    private String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    private String accessKeyId = "xxxxxxxxxxxx";
    private String accessKeySecret = "xxxxxxxxxxxxxxxxxx";
    private String bucketName = "xxxxxxxxxxx";
    private String firstKey = "xxxxxxxxxxxxx";

    /**oss获取文件流
     * @param filePath
     * @return
     */
    public InputStream getossFileStream(String filePath) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            OSSObject ossObject = ossClient.getObject(bucketName, firstKey+filePath);
            InputStream inputStream = ossObject.getObjectContent();
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
    
    /**oss获取文件下载路径;
     * @param keyname
     * @return
     */
    public URL getUrl(String keyname){
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 10000);
        // 生成URL
        URL url = client.generatePresignedUrl(bucketName, firstKey+keyname, expiration);
        return url;
    }
    
    /**OSS上传文件流
     * @param bucketName
     * @param filePathName
     * @param inputStream
     * @return
     */
    public URL uploadFileStream(String bucketName,String filePathName,InputStream inputStream){
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if(!client.doesBucketExist(bucketName)){
            client.createBucket(bucketName);
        }
        PutObjectResult por = client.putObject(bucketName, filePathName, inputStream);
        //获取该文件在阿里云的路径
        URL url=getUrl(filePathName);
        client.shutdown();
        return url;
    }
    
    /**oss上传文件
     * @param bucketName
     * @param filePathName
     * @param file
     * @return
     */
    public URL uploadFile(String bucketName,String filePathName,File file){
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if(!client.doesBucketExist(bucketName)){
            client.createBucket(bucketName);
        }
        PutObjectResult por = client.putObject(bucketName, filePathName, file);
        //获取该文件在阿里云的路径
        URL url=getUrl(filePathName);
        client.shutdown();
        return url;
    }
}
 


    com.aliyun.oss
    aliyun-sdk-oss
    3.5.0

以上就是oss操作直接调用方法即可;

 

你可能感兴趣的:(对对碰-java)