赞
踩
- 根据File文件对象信息创建DiskFileItem对象。
- 将File文件内容写入到DiskFileItem对象。
- 将DiskFileItem对象作为参数放入CommonsMultipartFile构造函数中来创建MultipartFile实例类对象。
代码示例如下:
public static MultipartFile convert(File file) throws IOException {
DiskFileItem fileItem = new DiskFileItem("file",
Files.probeContentType(file.toPath()), false,
file.getName(), (int) file.length(), file.getParentFile());
IoUtil.copy(Files.newInputStream(file.toPath()), fileItem.getOutputStream());
return new CommonsMultipartFile(fileItem);
}
实现输入流和文件名称转换成MultipartFile,代码示例如下:
public static MultipartFile covertMultipartFile(InputStream inputStream, String fileName) throws IOException { Assert.notNull(inputStream, "InputStream must not be null"); Assert.notBlank(fileName, "fileName must not be null"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); DiskFileItem fileItem = (DiskFileItem) fileItemFactory.createItem("file", MediaType.ALL_VALUE, true, fileName); try (OutputStream outputStream = fileItem.getOutputStream()) { IOUtils.copy(inputStream, outputStream); fileItem.getOutputStream().flush(); IOUtils.closeQuietly(inputStream); } catch (IOException e) { throw new RuntimeException(e); } if (fileItem.getSize() == 0) { throw new IOException("文件读取失败"); } return new CommonsMultipartFile(fileItem); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。