CommonsMultipartFile大小为0

时间:2017-02-15 15:05:25

标签: java multipart

我尝试此代码并且图像存在,但是当我尝试创建CommonsMultipartFile时,大小为零。

File file = new File("[image]");
DiskFileItem fileItem = new DiskFileItem("file", "image/png", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

1 个答案:

答案 0 :(得分:0)

你可以试试这个

DiskFileItem fileItem = new DiskFileItem("file", "image/png", true, file.getName(), (int)file.length() , file.getParentFile());
InputStream input =  new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
int ret = input.read();
while ( ret != -1 )
{
    os.write(ret);
    ret = input.read();
}
os.flush();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
Assert.assertTrue(multipartFile.getSize() > 0);