zoukankan      html  css  js  c++  java
  • file 转 MultipartFile

    • 文件转换 file 转 MultipartFile

    代码:

    /**
    * @Description file 转 MultipartFile
    * @author wjl
    * @date 2019/8/23 0023
    * @param [file]
    * @return org.springframework.web.multipart.MultipartFile
    */
    public static MultipartFile fileToMultiPartFile(File file){
    LocalDateTime localDateTime=LocalDateTime.now();
    String fileExt=localDateTime.getYear()+"-"+localDateTime.getMonth().getValue()+"-"+localDateTime.getDayOfMonth()+"-";
    MultipartFile multipartFile=new MultipartFile() {
    @Override
    public String getName() {
    return fileExt+file.getName();
    }
    
    @Override
    public String getOriginalFilename() {
    return fileExt+file.getName();
    }
    
    @Override
    public String getContentType() {
    return null;
    }
    
    @Override
    public boolean isEmpty() {
    
    return file==null ? true :false;
    }
    
    @Override
    public long getSize() {
    return 0;
    }
    
    @Override
    public byte[] getBytes() {
    return File2byte(file);
    }
    
    @Override
    public InputStream getInputStream() throws IOException {
    return new FileInputStream(file);
    }
    
    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
    
    }
    };
    
    return multipartFile;
    }
    • 文件转字数组
    /**
    * 将文件转字节数组
    * @param filePath
    * @return
    */
    public static byte[] File2byte(File tradeFile){
    byte[] buffer = null;
    try
    {
    FileInputStream fis = new FileInputStream(tradeFile);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int n;
    while ((n = fis.read(b)) != -1)
    {
    bos.write(b, 0, n);
    }
    fis.close();
    bos.close();
    buffer = bos.toByteArray();
    }catch (FileNotFoundException e){
    e.printStackTrace();
    }catch (IOException e){
    e.printStackTrace();
    }
    return buffer;
    }
    
     
  • 相关阅读:
    mktemp -t -d用法
    使用getopts处理输入参数
    linux中$1的意思
    linux中的set -e 与set -o pipefail
    在windows 7 和linux上安装xlwt和xlrd
    nginx map使用方法
    Linux crontab下关于使用date命令和sudo命令的坑
    东哥讲义
    ldapsearch使用
    date 命令之日期和秒数转换
  • 原文地址:https://www.cnblogs.com/wangsr-suc/p/11412056.html
Copyright © 2011-2022 走看看