SpringBoot如何上傳圖片
1.前端準(zhǔn)備
<%@ 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>實(shí)現(xiàn)文件長傳</h1> <!--enctype='開啟多媒體標(biāo)簽' --> <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.實(shí)現(xiàn)文件上傳的步驟說明
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方式上傳的文件,包含二進(jìn)制數(shù)據(jù)+文件名稱。
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() 方法創(chuàng)建多級目錄
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. 返回客戶端文件系統(tǒng)中的原始文件名。
String fileName = fileImage.getOriginalFilename(); File imageFile = new File(fileDir+'/'+fileName);
3.4 文件的上傳
fileImage.getOriginalFilename()//Transfer the received file to the given destination file. 將接收到的文件傳輸?shù)浇o定的目標(biāo)文件。
try { fileImage.transferTo(imageFile);//Transfer the received file to the given destination file. }catch(IOException e){ e.printStackTrace(); }
以上就是SpringBoot如何上傳圖片的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 上傳圖片的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程2. jsp文件下載功能實(shí)現(xiàn)代碼3. 如何在jsp界面中插入圖片4. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享5. 詳解瀏覽器的緩存機(jī)制6. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法7. Xml簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理8. phpstudy apache開啟ssi使用詳解9. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器10. JSP之表單提交get和post的區(qū)別詳解及實(shí)例
