如何将多部分文件转换为文件?

Ami*_*oda 75 java spring file-upload spring-mvc cloudinary

任何人都可以告诉我将多部分文件(org.springframework.web.multipart.MultipartFile)转换为File(java.io.File)的最佳方法是什么?

在我的春季mvc web项目中,我将上传文件作为Multipart文件.我必须将其转换为File(io),因此我可以调用此图像存储服务(Cloudinary).它们只采用类型(文件).

我做了很多搜索但是失败了.如果有人知道一个很好的标准方式,请告诉我?日Thnx

Pet*_*nis 174

您可以MultipartFile使用该getBytes方法获取内容,并可以Files.newOutputStream()使用MultipartFile该类创建该类的实例.

public void write(MultipartFile file, Path dir) {
    Path filepath = Paths.get(dir.toString(), file.getOriginalFilename();

    try (OutputStream os = Files.newOutputStream(filepath)) {
        os.write(file.getBytes());
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用transferTo方法:

public void multipartFileToFile(
    MultipartFile multipart, 
    Path dir
) throws IOException {
    Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
    multipart.transferTo(filepath);
}
Run Code Online (Sandbox Code Playgroud)

  • 我使用transferTo函数,但我觉得有问题.喜欢它保持临时文件驱动本地机器. (7认同)
  • `createNewFIle()`在这里毫无意义且浪费.您现在要求`new FileOutputStream()`(通过操作系统)删除如此创建的文件*并*创建一个新文件. (5认同)

Hei*_*erg 14

虽然接受的答案是正确的,但如果您只是想将图像上传到cloudinary,那么有一种更好的方法:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());
Run Code Online (Sandbox Code Playgroud)

其中multipartFile是你的org.springframework.web.multipart.MultipartFile.


and*_*rej 11

MultipartFile.transferTo(File) 很好,但毕竟不要忘记清理临时文件。

// ask JVM to ask operating system to create temp file
File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_POSTFIX);

// ask JVM to delete it upon JVM exit if you forgot / can't delete due exception
tempFile.deleteOnExit();

// transfer MultipartFile to File
multipartFile.transferTo(tempFile);

// do business logic here
result = businessLogic(tempFile);

// tidy up
tempFile.delete();
Run Code Online (Sandbox Code Playgroud)

在下面查看 Razzlero 关于在 JVM 退出时执行的 File.deleteOnExit() 的评论(这可能非常罕见)详细信息。

  • `deleteOnExit()`,它只会在 JVM 终止时触发,因此在异常期间不会触发。因此,在长时间运行的应用程序(例如服务器应用程序)上使用“deleteOnExit()”时需要小心。对于服务器应用程序,JVM 很少会退出。所以你需要小心`deleteOnExit()`导致内存泄漏。JVM 需要跟踪退出时需要删除的所有文件,这些文件由于 JVM 不会终止而未被清除。 (3认同)

Swa*_*shi 10

@PetrosTsialiamanis帖子上的小修正, new File( multipart.getOriginalFilename())这将在服务器位置创建文件,有时您将面临用户的写权限问题,并不总是可以为每个执行操作的用户提供写入权限. System.getProperty("java.io.tmpdir")将创建临时目录,您的文件将正确创建.这样您就可以创建临时文件夹,在其中创建文件,稍后您可以删除文件或临时文件夹.

public  static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException {
    File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName);
    multipart.transferTo(convFile);
    return convFile;
}
Run Code Online (Sandbox Code Playgroud)

将此方法放在常用实用程序中,并将其用于例如. Utility.multipartToFile(...)

  • 这应该是正确的答案(特别是对于使用 tmp 目录,因为它将解决一些问题,例如 Linux 中的权限被拒绝) (3认同)

小智 10

  private File convertMultiPartToFile(MultipartFile file ) throws IOException
    {
        File convFile = new File( file.getOriginalFilename() );
        FileOutputStream fos = new FileOutputStream( convFile );
        fos.write( file.getBytes() );
        fos.close();
        return convFile;
    }
Run Code Online (Sandbox Code Playgroud)


Geo*_*lou 9

您还可以使用Apache Commons IO库和FileUtils 类。如果您使用的是 maven,则可以使用上述依赖项加载它。

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

MultipartFile 保存到磁盘的源。

File file = new File(directory, filename);

// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);

// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
Run Code Online (Sandbox Code Playgroud)