威望0
积分7946
贡献0
在线时间763 小时
UID1
注册时间2021-4-14
最后登录2024-11-21
管理员
- UID
- 1
- 威望
- 0
- 积分
- 7946
- 贡献
- 0
- 注册时间
- 2021-4-14
- 最后登录
- 2024-11-21
- 在线时间
- 763 小时
|
[mw_shl_code=java,true]package com.mygeed.smart.core.core.utils.poi;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* `7MMM. ,MMF'`YMM' `MM' .g8"""bgd `7MM"""YMM `7MM"""YMM `7MM"""Yb.
* MMMb dPMM VMA ,V .dP' `M MM `7 MM `7 MM `Yb.
* M YM ,M MM VMA ,V dM' ` MM d MM d MM `Mb
* M Mb M' MM VMMP MM MMmmMM MMmmMM MM MM
* M YM.P' MM MM MM. `7MMF' MM Y , MM Y , MM ,MP
* M `YM' MM MM `Mb. MM MM ,M MM ,M MM ,dP'
*.JML. `' .JMML. .JMML. `"bmmmdPY .JMMmmmmMMM .JMMmmmmMMM .JMMmmmdP' Art By Jack Wu
*
* @Author Jack Wu
* @Link 微信号:MYGEEDS
* QQ:871213180
* @Descrition 对象File转换MultipartFile对象方法
*
*/
public class File2MultiPartFile<T> {
private static final Logger log = LoggerFactory.getLogger(File2MultiPartFile.class);
/**
* 对象File转换MultipartFile对象方法
*
* @param file
* @return
*/
public MultipartFile convert(File file) {
try {
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null)
file.deleteOnExit();
}
}
/**
* File对象转FileItem对象方法
*
* @param file
* @return
*/
private FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
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();
}
return item;
}
}[/mw_shl_code] |
|