封装MultipartFile参数(File转Multipart

2020-05-25  本文已影响0人  cherishpf
// 第一种方式
public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
            , MediaType.MULTIPART_FORM_DATA_VALUE
            , true
            , file.getName());
        try (InputStream input = new FileInputStream(file);
            OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
// 第二种方式
public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
            , MediaType.MULTIPART_FORM_DATA_VALUE
            , true
            , file.getName()
            , (int)file.length()
            , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

调用时:

File file = new File("C:\\Users\\YYY\\Desktop\\2020-05-1901.txt");
MultipartFile cMultiFile = getMultipartFile(file);

// 第三种方式

// 创建FileItem
    public static FileItem createFileItem(String filePath, String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

调用时:

File file = new File("C:\\Users\\YYY\\Desktop\\2020-05-1901.txt");
FileItem fileItem = createFileItem(file.getPath(),file.getName());
MultipartFile cMultiFile = new CommonsMultipartFile(fileItem);

// 第四种方式:
pom.xml添加依赖:

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
</dependency>
import org.springframework.mock.web.MockMultipartFile;

File file = new File("C:\\Users\\YYY\\Desktop\\2020-05-1901.txt");
MultipartFile cMultiFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
上一篇 下一篇

猜你喜欢

热点阅读