springboot进行图片上传并访问资源
生活随笔
收集整理的這篇文章主要介紹了
springboot进行图片上传并访问资源
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.前后端不分離:
springboot項目中static目錄下新建upload.html(導入thymeleaf依賴)
可以對上傳的文件進行配置:
html:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"><input type="file" name="uploadFile" value="選擇文件"><input type="submit" value="上傳"> </form> </body> </html>controller:
@PostMapping("/upload")public String upload(MultipartFile uploadFile,HttpServletRequest req){SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");String format = sdf.format(new Date());File folder = new File(realPath + format);if(!folder.isDirectory())folder.mkdirs();String oldName = uploadFile.getOriginalFilename();String newName = "nice" + oldName.substring(oldName.lastIndexOf("."),oldName.length());try{uploadFile.transferTo(new File(folder,newName));String filePath =req.getScheme() + "://" + req.getServerName() +":"+req.getServerPort()+"/uploadFile/" + format+newName;return filePath;}catch (IOException e){e.printStackTrace();} return "上傳失敗";}然后輸入地址:
選擇圖片點擊上傳后:
然后瀏覽器輸入:
同時可以在html中用img標簽訪問,輸入上面的url也可以訪問到
總結
以上是生活随笔為你收集整理的springboot进行图片上传并访问资源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【笔记】mybatis的sqlSessi
- 下一篇: shell的学习和命令使用入门