| | |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.io.OutputStream; |
| | | import java.net.URL; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.nio.file.Paths; |
| | | import java.nio.file.StandardCopyOption; |
| | | import java.util.Base64; |
| | | import java.util.Date; |
| | | import java.util.UUID; |
| | |
| | | objectMetadata.setContentType(fileType); |
| | | //上传文件 |
| | | PutObjectResult putResult = cosClient.putObject(cosConfig.getBucketName(), filePath, inputStream, objectMetadata); |
| | | TFile tFile = new TFile(); |
| | | tFile.setFileName(filePath); |
| | | tFile.setRealName(originalFilename); |
| | | tFile.setFileType(fileType); |
| | | tFile.setUrl(cosConfig.getRootSrc()+filePath); |
| | | tFile.setContentType(file.getContentType()); |
| | | tFile.setFileSize(file.getSize()); |
| | | sysFileService.save(tFile); |
| | | // 创建文件的网络访问路径 |
| | | String url = cosConfig.getRootSrc() + filePath; |
| | | return url; |
| | |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 将文件下载到指定目录 |
| | | * @param fileUrl |
| | | * @param saveDir |
| | | * @param fileName |
| | | * @throws IOException |
| | | */ |
| | | public void download(String fileUrl, String saveDir, String fileName){ |
| | | fileUrl = fileUrl.replace(cosConfig.getRootSrc(), ""); |
| | | // 下载文件并获取输入流 |
| | | COSObject object = cosClient.getObject(cosConfig.getBucketName(),fileUrl); |
| | | try ( |
| | | InputStream in = object.getObjectContent(); |
| | | ){ |
| | | Path targetPath = Paths.get(saveDir, fileName); |
| | | // 确保目录存在 |
| | | Files.createDirectories(targetPath.getParent()); |
| | | // 将文件保存到目标路径 |
| | | Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING); |
| | | }catch (IOException e){ |
| | | log.error("读取cos图片发生异常", e); |
| | | } |
| | | } |
| | | |
| | | |
| | | } |