123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package org.springblade.common.utils;
- import lombok.SneakyThrows;
- 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<FileSize> getOssFileSize(List<String> fileList){
- List<FileSize> reData =new ArrayList<>();
- if(fileList!=null){
- for(String fileUrl:fileList){
- 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 String getOssFileSizeCount(List<String> fileList){
- Long count = 0L;
- if(fileList!=null){
- for(String fileUrl:fileList){
- try {
- URLConnection openConnection = new URL(fileUrl).openConnection();
- count += openConnection.getContentLength();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return formatSize(count);
- }
- /**
- * 根据字节返回文件大小
- */
- private 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;
- }
- }
|