| | |
| | | import com.qcloud.cos.ClientConfig; |
| | | import com.qcloud.cos.auth.BasicCOSCredentials; |
| | | import com.qcloud.cos.auth.COSCredentials; |
| | | import com.qcloud.cos.exception.CosClientException; |
| | | import com.qcloud.cos.exception.CosServiceException; |
| | | import com.qcloud.cos.http.HttpProtocol; |
| | | import com.qcloud.cos.model.COSObject; |
| | | import com.qcloud.cos.model.GetObjectRequest; |
| | | import com.qcloud.cos.model.ObjectMetadata; |
| | | import com.qcloud.cos.model.PutObjectResult; |
| | | import com.qcloud.cos.region.Region; |
| | | import com.qcloud.cos.utils.IOUtils; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Component; |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.util.UUID; |
| | | |
| | |
| | | */ |
| | | @Value("${cos.client.bucket}") |
| | | private String bucketName; |
| | | /** |
| | | * 文件存放位置 |
| | | */ |
| | | @Value("${cos.client.location}") |
| | | private String location; |
| | | |
| | | /** |
| | | * 1.调用静态方法getCosClient()就会获得COSClient实例 |
| | |
| | | //使用UUID工具 创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型 |
| | | String fileName = UUID.randomUUID() + fileType; |
| | | // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字 |
| | | String key = "xizang/" + fileName; |
| | | String key = location+"/" + fileName; |
| | | // 创建上传Object的Metadata |
| | | ObjectMetadata objectMetadata = new ObjectMetadata(); |
| | | // - 使用输入流存储,需要设置请求长度 |
| | |
| | | return null; |
| | | } |
| | | } |
| | | // https://xzgttest-1305134071.cos.ap-chengdu.myqcloud.com/xizang/e4ea88b8-5470-456e-bf97-75cf47f38e84.jpg |
| | | public static void main(String[] args) throws IOException { |
| | | // 1 初始化用户身份信息(secretId, secretKey)。 |
| | | COSCredentials cred = new BasicCOSCredentials( |
| | | "AKIDCF5EF2c0DE1e5JK8r4EGJF4mNsMgp26x", |
| | | "lLl184rUyFOOE0d5KNGC3kmfNsCWk4GU"); |
| | | // 2.1 设置存储桶的地域(上文获得) |
| | | Region region = new Region("ap-chengdu"); |
| | | ClientConfig clientConfig = new ClientConfig(region); |
| | | // 2.2 使用https协议传输 |
| | | clientConfig.setHttpProtocol(HttpProtocol.https); |
| | | COSClient cosClient = new COSClient(cred, clientConfig); |
| | | String key = "xizang/e4ea88b8-5470-456e-bf97-75cf47f38e84.jpg"; |
| | | try { |
| | | // 5. 下载文件并获取输入流 |
| | | InputStream inputStream = cosClient.getObject("xzgttest-1305134071", key).getObjectContent(); |
| | | // 6. 处理输入流,例如读取内容或保存到本地文件 |
| | | // 这里仅作示例,实际应用中需要根据需求处理输入流 |
| | | byte[] buffer = new byte[1024]; |
| | | int len; |
| | | while ((len = inputStream.read(buffer)) != -1) { |
| | | // 处理读取到的数据 |
| | | System.out.write(buffer, 0, len); |
| | | } |
| | | System.err.println(buffer); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } finally { |
| | | // 7. 关闭输入流 |
| | | cosClient.shutdown(); |
| | | } |
| | | } |
| | | |
| | | } |