美文网首页
封装MultipartFile参数(File转Multipart

封装MultipartFile参数(File转Multipart

作者: cherishpf | 来源:发表于2020-05-25 11:52 被阅读0次
// 第一种方式
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));

相关文章

网友评论

      本文标题:封装MultipartFile参数(File转Multipart

      本文链接:https://www.haomeiwen.com/subject/qsxyahtx.html