当我读取相同的输入流时,我必须从 jsp 页面上传一些文件。
我正在检查它的真实性,它是否是一个有效的文件,因为我正在使用 jmimemagic
它接受输入流作为参数,现在当我尝试上传它时,它只上传 1 个字节的数据?
我觉得输入流有问题,请问有什么解决方案吗?
//For checking the file type
InputStream loIns = aoFileStream.getInputStreamToReadFile();
byte[] fileArray = IOUtils.toByteArray(loIns);
mimeType = Magic.getMagicMatch(fileArray, true).getMimeType();
if(!loAllowedFileTypesMimeList.contains(mimeType)){
return false;
}else{
String lsFileName = aoFileStream.getFileName();
String lsFileExt = lsFileName.substring(lsFileName.lastIndexOf(".") + 1);
if(loAllowedFileTypesList.contains(lsFileExt.toLowerCase())){
return true;
}
return false;
}
// For uploading the content
File loOutputFile = new File(asFilePathToUpload);
if(!loOutputFile.exists()){
FileOutputStream loOutput = new FileOutputStream(loOutputFile);
while (liEnd != -1) {
liEnd = inputStreamToReadFile.read();
loOutput.write(liEnd);
}
inputStreamToReadFile.close();
loOutput.close();
}
最佳答案
在
byte[] fileArray = IOUtils.toByteArray(loIns);
您已经耗尽了输入流,因此当您想将其写入文件时,您应该使用 fileArray
的内容,而不是您的 loIns
:
FileUtils.writeByteArrayToFile(loOutput, fileArray);
FileUtils 由 apache-commons 提供
关于Java文件上传-输入流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10188898/