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

谁能告诉我转换多部分文件(org.springframework.web.multipart)的最佳方法是什么。多部分文件)到文件(java.io。档案) ?

在我的春季 mvc 网络项目,我得到上传的文件作为 Multipart 文件。我必须把它转换成一个文件(io) ,因此,我可以调用这个图像存储服务(迷雾)。他们只采取类型(文件)。

我已经做了这么多的搜索,但失败了。如果有人知道一个好的标准方法,请让我知道? 谢谢

286775 次浏览

You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream():

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());
}
}

You can also use the transferTo method:

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

You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

The source for the MultipartFile save to disk.

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());

You can access tempfile in Spring by casting if the class of interface MultipartFile is CommonsMultipartFile.

public File getTempFile(MultipartFile multipartFile)
{
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);


//trick to implicitly save on disk small files (<10240 bytes by default)
if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}


return file;
}

To get rid of the trick with files less than 10240 bytes maxInMemorySize property can be set to 0 in @Configuration @EnableWebMvc class. After that, all uploaded files will be stored on disk.

@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(0);
return resolver;
}

Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());

Where multipartFile is your org.springframework.web.multipart.MultipartFile.

The answer by Alex78191 has worked for me.

public File getTempFile(MultipartFile multipartFile)
{


CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);


//trick to implicitly save on disk small files (<10240 bytes by default)


if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}


return file;
}

For uploading files having size greater than 10240 bytes please change the maxInMemorySize in multipartResolver to 1MB.

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size t 20MB -->
<property name="maxUploadSize" value="20971520" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" />
<!-- 1MB --> </bean>

small correction on @PetrosTsialiamanis post , new File( multipart.getOriginalFilename()) this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action. System.getProperty("java.io.tmpdir") will create temp directory where your file will be created properly. This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.

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;
}

put this method in ur common utility and use it like for eg. Utility.multipartToFile(...)

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;
}

MultipartFile.transferTo(File) is nice, but don't forget to clean the temp file after all.

// 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();

Check out Razzlero's comment about File.deleteOnExit() executed upon JVM exit (which may be extremely rare) details below.

if you don't want to use MultipartFile.transferTo(). You can write file like this

    val dir = File(filePackagePath)
if (!dir.exists()) dir.mkdirs()


val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
createNewFile()
}


FileOutputStream(file).use {
it.write(multipartFile.bytes)
}

Single line answer using Apache Commons.

FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);

MultipartFile can get InputStream.

multipartFile.getInputStream()