java中文件上传下载将file转为MultipartFile

方式1:简单明了

jar包依赖:

复制代码
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpcore</artifactId>
  <version>4.4.9</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.1.6.RELEASE</version>
</dependency>
复制代码

代码

File pdfFile = new File("D://test.pdf");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
   ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

 

方式2:不用引入新包

复制代码
public static MultipartFile fileToMultipartFile(File file) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory(16, null);
    FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    try {
        FileInputStream fis = new FileInputStream(file);
        OutputStream os = item.getOutputStream();
        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    MultipartFile multipartFile = new CommonsMultipartFile(item);
    return  multipartFile;

}
复制代码

 

posted @   满Sir  阅读(784)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示