-上傳
–上傳前臺代碼
<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);
}