java 多部分文件到文件输入流

k4ymrczo  于 2023-04-19  发布在  Java
关注(0)|答案(8)|浏览(149)

如何将内存中的MultipartFile转换为FileInputStream
我试着在下面,但我面临的错误作为
无法将org.springframework.web.multipart.commons.CommonsMultipartFile强制转换为java.io.File
我的代码是

FileInputStream fis = new FileInputStream((File)file);

其中file是多部分文件

ngynwnxp

ngynwnxp1#

你不能创建FileInputStream的示例,除非你的文件不在文件系统中。
您必须首先将多部分文件保存在服务器上的临时位置

file.transferTo(tempFile);
InputStream stream = new FileInputStream(tempFile);

但是多部分文件也可以通过基本的流方法读取,例如

InputStream inputStream =  new BufferedInputStream(file.getInputStream());
rjee0c15

rjee0c152#

尝试使用:

MultipartFile uploadedFile = ((MultipartHttpServletRequest)request).getFile('file_name')
InputStream inputStream = new ByteArrayInputStream(uploadedFile?.getBytes())
tyu7yeag

tyu7yeag3#

查看MultipartFile
在这一点上,您可以使用:

void    transferTo(File dest)

此方法将接收到的文件传输到给定的目标文件。

juud5qan

juud5qan4#

MultipartFile file;
InputStream inputStream = file.getInputStream();
3wabscal

3wabscal5#

将多部分文件转换为输入流

MultipartFile file;
InputStream inputStream = new InputStream(file.getInputStream());

这对我很有效。

jtjikinw

jtjikinw6#

我们可以像下面这样进行造型和使用

FileInputStream file = (FileInputStream) multipartFile.getInputStream();
3z6pesqy

3z6pesqy7#

``String filename = file.getOriginalFilename();

    Random val = new Random();

    int randomNumber = val.nextInt(999999);

    String filePath = path + File.separator + randomNumber+filename;

    file.transferTo(Paths.get(filePath));``

**注意:**生成相应的文件发送目标路径,并使用Multipartfile对象file. transferTo()方法。它的copy() copy方法的替代方法使我在运行时出错,因此复制和存储图像的最佳方法是使用file.transferTo()对象。

enxuqcxy

enxuqcxy8#

对于多部分文件,例如:

FileMultipartData part =  new FileMultipartData();
InputStream inputStream = part.getFileMultipart().get(0).getByteStream();

这在我的代码中对我有效。请尝试一下

相关问题