EN
/news/show.php/video/24914315.html

java:File和MultipartFile互转

2025-06-24 12:12:43 来源: 新华社
字号:默认 超大 | 打印 |

1 概述。

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

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

2 代码示例。

2.1 引入依赖。

					org.springframework			spring-test			5.1.9.RELEASE			compile		

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 转换为 MultipartFile    private  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;    }。

【我要纠错】责任编辑:新华社