MultipartFile和File互转工具类

MultipartFile和File互转工具类_hutool multipartfile 转file_苍穹之跃的博客-CSDN博客

上面的不能转视频,只能文档


            org.apache.httpcomponents
            httpmime
            4.5.8
        
 
            cn.hutool
            hutool-all
            5.7.22
        

下面的可以视频可以文档

package com.unicom.park.core.util;
 
import cn.hutool.core.io.unit.DataSize;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.common.collect.ImmutableList;
import javafx.util.Duration;
import org.apache.catalina.Manager;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import  java.io.File;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * MultipartFile和File互转工具类
 */
public class MultipartFileUtil {
 
    /**
     * 输入流转MultipartFile
     *
     * @param fileName
     * @param inputStream
     * @return
     */
    public static MultipartFile getMultipartFile(String fileName, InputStream inputStream) {
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(fileName, fileName,
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
 
    /**
     * 读取网络文件
     *
     * @param url      文件地址
     * @param fileName 文件名称(需带文件名后缀)
     * @return
     */
    public static MultipartFile getMultipartFile(String url, String fileName) {
        HttpResponse response = HttpRequest.get(url).execute();
        InputStream inputStream = response.bodyStream();
        return MultipartFileUtil.getMultipartFile(fileName, inputStream);
    }

    /**
     * File 转MultipartFile
     *
     * @param file
     * @return
     */
    public static MultipartFile getMultipartFile(File file) {
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
 
    /**
     * MultipartFileUtil 转File
     *
     * @param multipartFile
     * @return
     */
    public static File getFile(MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = "." + getExtensionName(fileName);
        File file = null;
        try {
            // 用uuid作为文件名,防止生成的临时文件重复
            file = File.createTempFile(IdUtil.simpleUUID(), prefix);
            // MultipartFile to File
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 获取文件扩展名,不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
        前端上传视频之后,根据上传的视频文件获取视频的大小和时长
        1、获取视频时长
    */
    public static int readVideoTime(File source) {
        int vedioSecond =  Integer.parseInt(parseDuration(source.getAbsolutePath()));
        return vedioSecond;
    }


    /**
     * 视频时长
     *
     * @param fileUrl
     * @return String[] 0=秒时长,1=展示时长(格式如 01:00:00)
     */
    public static String parseDuration(String fileUrl) {
        long ls = 0L;
        String[] length = new String[2];
        try {
            //
//            URL source = new URL(fileUrl);
            // 构造方法 接受URL对象
//            MultimediaObject instance = new MultimediaObject(source);
            // 构造方法 接受File对象
            MultimediaObject instance = new MultimediaObject(new File(fileUrl));
            MultimediaInfo result = instance.getInfo();
            ls = result.getDuration() / 1000;
            length[0] = String.valueOf(ls);
            Integer hour = (int) (ls / 3600);
            Integer minute = (int) (ls % 3600) / 60;
            Integer second = (int) (ls - hour * 3600 - minute * 60);
            String hr = hour.toString();
            String mi = minute.toString();
            String se = second.toString();
            if (hr.length() < 2) {
                hr = "0" + hr;
            }
            if (mi.length() < 2) {
                mi = "0" + mi;
            }
            if (se.length() < 2) {
                se = "0" + se;
            }

            String noHour = "00";
            if (noHour.equals(hr)) {
                length[1] = mi + ":" + se;
            } else {
                length[1] = hr + ":" + mi + ":" + se;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(length);//{"20","00:20"}
        return String.valueOf(ls);
    }



 


    /**
     * 2、获取文件大小
     * @param source
     * @return
     * //***获取视频大小的时候,由于用到了流,使用完之后一定要及时的关闭流,避免无法删除视频文件***
     *
     */
    public static BigDecimal readFileSize(File source) {
        //cn.hutool.core.io.unit.DataSize.ofMegabytes()
        FileChannel fc= null;
        //String size = "";
        BigDecimal  size  = null ;
        try {
            @SuppressWarnings("resource")
            FileInputStream fis = new FileInputStream(source);
            fc= fis.getChannel();
            BigDecimal fileSize = new BigDecimal(fc.size());
            //size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
            size = fileSize.divide(new BigDecimal(1024*1024), 2, RoundingMode.HALF_UP)  ;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null!=fc){
                try{
                    fc.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return size;
    }


}

可以转换文档可以转换视频

          
            
                 ws.schild
                jave-all-deps
                2.6.0
            
package com.unicom.park.core.util;
 
import cn.hutool.core.io.unit.DataSize;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.common.collect.ImmutableList;
import javafx.util.Duration;
import org.apache.catalina.Manager;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import  java.io.File;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * MultipartFile和File互转工具类
 */
public class MultipartFileUtil {
 
    /**
     * 输入流转MultipartFile
     *
     * @param fileName
     * @param inputStream
     * @return
     */
    public static MultipartFile getMultipartFile(String fileName, InputStream inputStream) {
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(fileName, fileName,
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
 
    /**
     * 读取网络文件
     *
     * @param url      文件地址
     * @param fileName 文件名称(需带文件名后缀)
     * @return
     */
    public static MultipartFile getMultipartFile(String url, String fileName) {
        HttpResponse response = HttpRequest.get(url).execute();
        InputStream inputStream = response.bodyStream();
        return MultipartFileUtil.getMultipartFile(fileName, inputStream);
    }

    /**
     * File 转MultipartFile
     *
     * @param file
     * @return
     */
    public static MultipartFile getMultipartFile(File file) {
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
 
    /**
     * MultipartFileUtil 转File
     *
     * @param multipartFile
     * @return
     */
    public static File getFile(MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = "." + getExtensionName(fileName);
        File file = null;
        try {
            // 用uuid作为文件名,防止生成的临时文件重复
            file = File.createTempFile(IdUtil.simpleUUID(), prefix);
            // MultipartFile to File
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 获取文件扩展名,不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
        前端上传视频之后,根据上传的视频文件获取视频的大小和时长
        1、获取视频时长
    */
    public static int readVideoTime(File source) {
        int vedioSecond =  Integer.parseInt(parseDuration(source.getAbsolutePath()));
        return vedioSecond;
    }


    /**
     * 视频时长
     *
     * @param fileUrl
     * @return String[] 0=秒时长,1=展示时长(格式如 01:00:00)
     */
    public static String parseDuration(String fileUrl) {
        long ls = 0L;
        String[] length = new String[2];
        try {
            //
//            URL source = new URL(fileUrl);
            // 构造方法 接受URL对象
//            MultimediaObject instance = new MultimediaObject(source);
            // 构造方法 接受File对象
            MultimediaObject instance = new MultimediaObject(new File(fileUrl));
            MultimediaInfo result = instance.getInfo();
            ls = result.getDuration() / 1000;
            length[0] = String.valueOf(ls);
            Integer hour = (int) (ls / 3600);
            Integer minute = (int) (ls % 3600) / 60;
            Integer second = (int) (ls - hour * 3600 - minute * 60);
            String hr = hour.toString();
            String mi = minute.toString();
            String se = second.toString();
            if (hr.length() < 2) {
                hr = "0" + hr;
            }
            if (mi.length() < 2) {
                mi = "0" + mi;
            }
            if (se.length() < 2) {
                se = "0" + se;
            }

            String noHour = "00";
            if (noHour.equals(hr)) {
                length[1] = mi + ":" + se;
            } else {
                length[1] = hr + ":" + mi + ":" + se;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(length);//{"20","00:20"}
        return String.valueOf(ls);
    }






    /**
     * 2、获取文件大小
     * @param source
     * @return
     * //***获取视频大小的时候,由于用到了流,使用完之后一定要及时的关闭流,避免无法删除视频文件***
     *
     */
    public static BigDecimal readFileSize(File source) {
        //cn.hutool.core.io.unit.DataSize.ofMegabytes()
        FileChannel fc= null;
        //String size = "";
        BigDecimal  size  = null ;
        try {
            @SuppressWarnings("resource")
            FileInputStream fis = new FileInputStream(source);
            fc= fis.getChannel();
            BigDecimal fileSize = new BigDecimal(fc.size());
            //size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
            size = fileSize.divide(new BigDecimal(1024*1024), 2, RoundingMode.HALF_UP)  ;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null!=fc){
                try{
                    fc.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return size;
    }


}

你可能感兴趣的:(算法)