1、所需jar
commons-fileupload-1.2.2.jar
2、轉換代碼
//本地文件轉爲MultipartFile類型(文件路徑)
private static MultipartFile getMulFileByPath(String picPath) {
FileItem fileItem = createFileItem(picPath);
MultipartFile mfile = new CommonsMultipartFile(fileItem);
return mfile;
}
private static FileItem createFileItem(String filePath)
{
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
FileItem item = factory.createItem(textFieldName, "text/plain", true,
"MyFileName" + extFile);
File newfile = new File(filePath);
long fileSize = newfile.length();
int bytesRead = 0;
byte[] buffer =new byte[(int) fileSize];
try
{
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, buffer.length))!= -1)
{
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return item;
}
3、調用
//讀取文件流
MultipartFile file = getMulFileByPath("文件路徑");