| | |
| | | import java.io.File; |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.net.URL; |
| | | import java.net.URLConnection; |
| | | import java.util.UUID; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Executors; |
| | |
| | | String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".")); |
| | | String key = java.util.UUID.randomUUID().toString() + fileExt; |
| | | |
| | | |
| | | ObjectMetadata metadata = new ObjectMetadata(); |
| | | metadata.setContentLength(file.getSize()); |
| | | metadata.setContentType(file.getContentType()); |
| | |
| | | |
| | | PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile); |
| | | cosClient.putObject(putObjectRequest); |
| | | return baseUrl + "/" + key; |
| | | return key; |
| | | } |
| | | |
| | | /** |
| | | * 上传本地文件 |
| | | * @param fileUrl 本地文件路径 |
| | | * @return 文件访问URL |
| | | */ |
| | | public String uploadWebFile(String fileUrl) throws IOException { |
| | | // 假设 fileUrl 是你要上传的文件 URL |
| | | System.out.println(fileUrl); |
| | | URL url = new URL(fileUrl); |
| | | InputStream inputStream = url.openStream(); |
| | | |
| | | URLConnection connection = url.openConnection(); |
| | | |
| | | // 获取文件的大小(字节数) |
| | | int contentLength = connection.getContentLength(); |
| | | // 获取文件类型 |
| | | String type = connection.getContentType(); |
| | | // 获取文件的扩展名(如果需要) |
| | | String fileExtension = fileUrl.substring(fileUrl.lastIndexOf(".")); |
| | | String key = UUID.randomUUID().toString() + fileExtension; |
| | | |
| | | ObjectMetadata metadata = new ObjectMetadata(); |
| | | metadata.setContentLength(contentLength); |
| | | metadata.setContentType(type); |
| | | // 创建 PutObjectRequest 请求对象,直接传入 InputStream |
| | | PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata); |
| | | |
| | | // 上传文件 |
| | | cosClient.putObject(putObjectRequest); |
| | | |
| | | // 关闭输入流 |
| | | inputStream.close(); |
| | | |
| | | return key; |
| | | } |
| | | |
| | | /** |