package org.springblade.common.utils; import lombok.SneakyThrows; import org.springblade.common.constant.CommonConstant; import org.springblade.common.vo.FileSize; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class FileUtils { /** * 获取文件path * * @param file * @return * @throws IOException */ public static File convert(MultipartFile file) throws IOException { File convertFile = new File(Objects.requireNonNull(Objects.requireNonNull(file.getOriginalFilename()))); FileOutputStream fos = null; try { convertFile.createNewFile(); fos = new FileOutputStream(convertFile); fos.write(file.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { assert fos != null; fos.close(); } return convertFile; } //获取文件大小 public static List getOssFileSize(List fileList) { List reData = new ArrayList<>(); if (fileList != null) { for (String fileUrl : fileList) { fileUrl = CommonUtil.replaceOssUrl(fileUrl); FileSize file = new FileSize(); file.setFileUrl(fileUrl); try { URLConnection openConnection = new URL(fileUrl).openConnection(); int contentLength = openConnection.getContentLength(); Double fileLength = Double.parseDouble(contentLength + ""); file.setFileSize(Math.ceil(fileLength / 1024)); } catch (IOException e) { e.printStackTrace(); } reData.add(file); } } return reData; } //获取OSS文件总大小 public static Long getOssFileSizeCount(List fileList) { Long count = 0L; if (fileList != null) { for (String fileUrl : fileList) { try { fileUrl = CommonUtil.replaceOssUrl(fileUrl); URLConnection openConnection = new URL(fileUrl).openConnection(); count += openConnection.getContentLength(); } catch (IOException e) { e.printStackTrace(); } } } return count; } /** * 根据字节返回文件大小 */ public static String formatSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; String wrongSize = "0B"; if (fileS == 0) { return wrongSize; } if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "KB"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "MB"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "GB"; } return fileSizeString; } }