/**
* file 转 MultipartFile
* @param filePath
* @return
*/
public MultipartFile fileToMultipartFile(String filePath) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
String myFileName = filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf("."));
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();
}
if(item != null){
MultipartFile multipartFile = new CommonsMultipartFile(item);
return multipartFile;
}
return null;
}
file转MultipartFile 需要jar包:jave-1.0.2.jar
最新推荐文章于 2024-04-13 08:10:21 发布