-上传
–上传前台代码
<input type="file" name="doc">
–后台代码
@RequestMapping("upload")
public String upload(Integer bid, MultipartFile doc, Model model) {
BankBean bank = new BankBean();
if (!doc.isEmpty()) {
// 获取路径
String filePath = "D:\\img\\upload\\";
String originalFilename = doc.getOriginalFilename();
// UUID随机重命名
String newFileName = (UUID.randomUUID() + originalFilename
.substring(originalFilename.indexOf("."))).replace("-", "");
// 新文件
File file = new File(filePath + newFileName);
// 将文件写入磁盘
try {
doc.transferTo(file);
// 将图片名字写入实体类
bank = bankService.getBankByBid(bid);
bank.setFileName(newFileName);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("文件为空");
model.addAttribute("bid", bid);
// 返回上传页面
return "upload";
}
// 将图片名字写入数据库
bankService.updateBank(bank);
// 返回列表页面查看
return "redirect:getBankList.action";
}
–前台展示图片代码
—-tomcat展示绝对路径时需要配置如下
在tomcat文件中conf文件夹下server.xml文件中的Host双标签中配置虚拟路径
<Host>
<Context path="/upload" docBase="D:\img\upload\" reloadable="true"></Context>
</Host>
–展示/下载前台
<c:if test="${b.fileName != null && b.fileName != '' }">
<a href="downLoad.action?fileName=${b.fileName }">
<img width="120px" height="80px" src="/upload/${b.fileName }">
</a>
</c:if>
–下载后台代码
@RequestMapping("downLoad")
public ResponseEntity<byte[]> download(String fileName) throws IOException {
String filePath = "D:\\img\\upload\\";
File file = new File(filePath + fileName);
// 处理显示中文文件名的问题
String newFilename = new String(fileName.getBytes("UTF-8"),
"iso-8859-1");
// 设置请求头内容,告诉浏览器代开下载窗口
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", newFilename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}