当前位置: 首页 > news >正文

java:File与MultipartFile互转

1 概述

当我们在处理文件上传的功能时,通常会使用MultipartFile对象来表示上传的文件数据。然而,有时候我们可能已经有了一个File对象,而不是MultipartFile对象,需要将File对象转换为MultipartFile对象进行进一步处理。

在Java中,File对象表示文件在本地文件系统中的引用,而MultipartFile对象是Spring框架提供的用于处理文件上传的接口。MultipartFile接口提供了许多有用的方法,例如获取文件名、获取文件内容、获取文件大小等。

2 代码示例

2.1 引入依赖

<!--File转MultipartFile需要test包--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version><scope>compile</scope></dependency>

2.2 MultipartFile转File

    public static File convert(MultipartFile file) throws IOException {File convFile = new File(file.getOriginalFilename());convFile.createNewFile();FileOutputStream fos = new FileOutputStream(convFile);fos.write(file.getBytes());fos.close();return convFile;}

2.3 File转MultipartFile

//file 转换为 MultipartFileprivate  MultipartFile getMulFileByPath(String filePath){FileItemFactory factory = new DiskFileItemFactory(16, null);String textFieldName = "textField";int num = filePath.lastIndexOf(".");String extFile = filePath.substring(num);FileItem item = factory.createItem(textFieldName, "text/plain", true,"MyFileName" + extFile);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);}os.close();fis.close();}catch (IOException e){e.printStackTrace();}MultipartFile mfile = new CommonsMultipartFile(item);return mfile;}

http://www.lryc.cn/news/415117.html

相关文章:

  • 高级java每日一道面试题-2024年8月04日-web篇-如果客户端禁止cookie能实现session还能用吗?
  • leetcode 107.二叉树的层序遍||
  • C++在网络安全领域的应用
  • Chapter 26 Python魔术方法
  • 基于Transformer的语音识别与音频分类
  • leetcode数论(1362. 最接近的因数)
  • sqli-labs-master less1-less6
  • 力扣287【寻找重复数】
  • 【2024蓝桥杯/C++/B组/传送阵】
  • (四十一)大数据实战——spark的yarn模式生产环境部署
  • 【深度学习实战(53)】classification_report()
  • 计算机网络基础之网络套接字socket编程(初步认识UDP、TCP协议)
  • 手撕Python!模块、包、库,傻傻分不清?一分钟带你弄明白!
  • Linux--序列化与反序列化
  • 使用C#和 aspose.total 实现替换pdf中的文字(外语:捷克语言的pdf),并生成新的pdf导出到指定路径
  • 【Material-UI】Autocomplete中的高亮功能(Highlights)详解
  • Android 11(R)启动流程 初版
  • 从零安装pytorch
  • 2024.07.28 校招 实习 内推 面经
  • python实现小游戏——植物大战僵尸(魔改版本)
  • 基于K210智能人脸识别+车牌识别系统(完整工程资料源码)
  • 8.怎么配嵌套子路由,以及它的作用
  • 【海贼王航海日志:前端技术探索】HTML你学会了吗?(二)
  • 体系结构论文导读(三十一)(下):Soft errors in DNN accelerators: A comprehensive review
  • Python在指定文件夹下创建虚拟环境
  • 【SpringBoot】 定时任务之任务执行和调度及使用指南
  • 理解 Objective-C 中 +load 方法的执行顺序
  • 切面条问题算法的详解
  • JNDI注入
  • SQL Server数据库文件过大而无法直接导出解决方案