SpringBoot如何上傳圖片
1.前端準備
<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'> <html> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <title>Insert title here</title> </head> <body> <h1>實現文件長傳</h1> <!--enctype='開啟多媒體標簽' --> <form action='http://localhost:8091/filetest' method='post' enctype='multipart/form-data'> <input name='fileImage' type='file' /> <input type='submit' value='提交'/> </form> </body> </html>
2.實現文件上傳的步驟說明
package com.jt.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @RestController public class FileTestController { @RequestMapping('/filetest') public String file(MultipartFile fileImage){ String fileDir = 'F:/CloudMusic/images'; File file = new File(fileDir); if(!file.exists()){ file.mkdirs(); } String fileName = fileImage.getOriginalFilename(); File imageFile = new File(fileDir+'/'+fileName); try { fileImage.transferTo(imageFile);//Transfer the received file to the given destination file. }catch(IOException e){ e.printStackTrace(); } return 'ok'; } }
3.代碼解釋
3.1 前提
MultipartFile是spring類型,代表HTML中form data方式上傳的文件,包含二進制數據+文件名稱。
public String file(MultipartFile fileImage){}<form action='http://localhost:8091/filetest' method='post' enctype='multipart/form-data'> <input name='fileImage' type='file' /> <input type='submit' value='提交'/> </form>
3.2 封裝文件的上傳路徑
封裝文件上傳的路徑,如果文件存在直接封裝,如果文件不存在使用 file.mkdirs() 方法創建多級目錄
String fileDir = 'F:/CloudMusic/images'; File file = new File(fileDir); if(!file.exists()){ file.mkdirs(); }
3.3 封裝文件的名稱
fileImage.getOriginalFilename()//Return the original filename in the client’s filesystem. 返回客戶端文件系統中的原始文件名。
String fileName = fileImage.getOriginalFilename(); File imageFile = new File(fileDir+'/'+fileName);
3.4 文件的上傳
fileImage.getOriginalFilename()//Transfer the received file to the given destination file. 將接收到的文件傳輸到給定的目標文件。
try { fileImage.transferTo(imageFile);//Transfer the received file to the given destination file. }catch(IOException e){ e.printStackTrace(); }
以上就是SpringBoot如何上傳圖片的詳細內容,更多關于SpringBoot 上傳圖片的資料請關注好吧啦網其它相關文章!
相關文章:
1. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)2. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法3. 一篇文章帶你了解JavaScript-對象4. IntelliJ IDEA設置條件斷點的方法步驟5. Python使用oslo.vmware管理ESXI虛擬機的示例參考6. Java構建JDBC應用程序的實例操作7. javascript設計模式 ? 建造者模式原理與應用實例分析8. Jsp中request的3個基礎實踐9. Spring應用拋出NoUniqueBeanDefinitionException異常的解決方案10. 淺談SpringMVC jsp前臺獲取參數的方式 EL表達式
