场景:
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver =
new CommonsMultipartResolver(request.getSession().getServletContext());
if (commonsMultipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
//从请求中分离出图片文件,形成的是CommonsMultipartFile类型文件
shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
}
//生成一个特定文件夹下的的随机文件名文件,用来转换
File shopImgFile = new File(PathUtil.getImgBasePath() + ImageUtil.getRandomFileName());
try {
shopImgFile.createNewFile();
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("error Message:", "shopImgFile 创建失败 : " + e.getMessage() );
return modelMap;
}
try {
//在这里使用
inputStreamToFile(shopImg.getInputStream(), shopImgFile);
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("error Message:", "inputStreamToFile 执行失败 :" + e.getMessage());
return modelMap;
}
//在shopService.addShop的方法中,第二个参数是File类型
ShopExecution shopExecution = shopService.addShop(shop, shopImgFile);
private static void inputStreamToFile(InputStream ins, File file) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = ins.read(buffer)) != 1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (ins != null) {
ins.close();
}
} catch (Exception e) {
throw new RuntimeException("关闭inputStreamToFile产生异常:" + e.getMessage());
}
}
}
使用inputStreamToFile这个方法就可以实现转换了(原理是因为CommonsMultipartFile类型有一个getInputStream()方法),可以获得文件流然后转换成File类型。