上传文件到本地
1.页面写法
<input type="file" name="photofile" id="photo" />
<form id="appForm" action="#springUrl('/')apps/update" method="post" enctype="multipart/form-data">
2.后台接受
@RequestParam(value = "photofile", required = false) MultipartFile photofile,
转换存入本地
//文件路径和文件名字
File file = new File(imgDir, filename);
//转化为file
if (null != multipartFile && !multipartFile.isEmpty()) {
multipartFile.transferTo(file);
}
分割文件路径的时候要注意File.separator
windows是\或/,unix是/ 使用File.separator完美解决
3.页面回显
<img src="#springUrl('/')apps/getPhoto/${app.id}" width="110" height="80" />
String img = null;
OutputStream os = null;
FileInputStream fis = null;
try {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
App app = sqlSession.selectOne(
"com.itrus.portal.db.AppMapper.selectByPrimaryKey", id);
if (null == app) {
return "status403";
}
img = app.getAppIcon();
if (img == null) {
return "status403";
}
//获得文件路径和名字
File filePath = appService.getFilePathById(id);
if (!filePath.exists()) {
filePath.mkdir();
}
File file = new File(filePath, img);
fis = new FileInputStream(file);
byte[] bb = IOUtils.toByteArray(fis);
os = response.getOutputStream();
os.write(bb);
os.flush();
} catch (IOException e) {// 未找到
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {// 关闭流!
try {
if (null != fis) {
fis.close();
}
if (null != os) {
os.close();
}
} catch (IOException e) {
}
}