• File转换为MultipartFile工具类


     1 package cn.com.utils;
     2 
     3 import org.apache.commons.fileupload.FileItem;
     4 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     5 import org.springframework.util.FileCopyUtils;
     6 import org.springframework.web.multipart.MultipartFile;
     7 import org.springframework.web.multipart.commons.CommonsMultipartFile;
     8 
     9 import javax.activation.MimetypesFileTypeMap;
    10 import java.io.ByteArrayInputStream;
    11 import java.io.File;
    12 import java.io.InputStream;
    13 import java.io.OutputStream;
    14 
    15 public class FileToMultipartFileUtil {
    16 
    17 
    18     public static MultipartFile toMultipartFile(String fieldName, File file) throws Exception {
    19         DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    20         String contentType = new MimetypesFileTypeMap().getContentType(file);
    21         FileItem fileItem = diskFileItemFactory.createItem(fieldName, contentType, false, file.getName());
    22         try (
    23                 InputStream inputStream = new ByteArrayInputStream(FileCopyUtils.copyToByteArray(file));
    24                 OutputStream outputStream = fileItem.getOutputStream()
    25         ) {
    26             FileCopyUtils.copy(inputStream, outputStream);
    27         } catch (Exception e) {
    28             throw e;
    29         }
    30         MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
    31         return multipartFile;
    32     }
    33 
    34 
    35     public static MultipartFile toMultipartFile(String fieldName, String fileName, byte[] fileByteArray) throws Exception {
    36         DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    37         String contentType = new MimetypesFileTypeMap().getContentType(fileName);
    38         FileItem fileItem = diskFileItemFactory.createItem(fieldName, contentType, false, fileName);
    39         try (
    40                 InputStream inputStream = new ByteArrayInputStream(fileByteArray);
    41                 OutputStream outputStream = fileItem.getOutputStream()
    42         ) {
    43             FileCopyUtils.copy(inputStream, outputStream);
    44         } catch (Exception e) {
    45             throw e;
    46         }
    47         MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
    48         return multipartFile;
    49     }
    50 
    51 }
  • 相关阅读:
    GIT → 04:Git与代码托管平台
    GIT → 03:Git的下载和安装
    GIT → 02:Git和Svn比较
    GIT → 01:学习版本控制的原因
    GIT → 00:GIT学习大纲
    GIT → 10:基于IntelliJ IDEA的Git 操作
    GIT → 11:Git 工作流与实战演练
    GIT → 09:TortoiseGit 图形化工具
    亚马逊服务器搭建pptp方法
    Safari获取UDID需要安装.mobileconfig文件,
  • 原文地址:https://www.cnblogs.com/bevis-byf/p/11658683.html
Copyright © 2020-2023  润新知