Spring Boot 實(shí)現(xiàn)圖片上傳并回顯功能
1 項(xiàng)目結(jié)構(gòu)
2 配置文件及環(huán)境設(shè)置
(1)配置文件
# 應(yīng)用服務(wù) WEB 訪問(wèn)端口server.port=8080# spring 靜態(tài)資源掃描路徑spring.resources.static-locations=classpath:/static/# 訪問(wèn)template下的html文件需要配置模板spring.thymeleaf.prefix.classpath=classpath:/templates/# 是否啟用緩存spring.thymeleaf.cache=false# 模板文件后綴spring.thymeleaf.suffix=.html# 模板文件編碼spring.thymeleaf.encoding=UTF-8#上傳的絕對(duì)路徑file.upload.path=G://images/ #最關(guān)鍵##絕對(duì)路徑下的相對(duì)路徑file.upload.path.relative=/images/** #最關(guān)鍵##設(shè)置文件最大值spring.servlet.multipart.max-file-size=5MB
在相關(guān)路徑新建文件夾
3 代碼
(1)pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
(2)index.html
<!DOCTYPE html><html lang='en' xmlns:th='http://www.w3.org/1999/xhtml'><head> <meta charset='UTF-8'> <title>Title</title></head><body><form action='../upload' method='post' enctype='multipart/form-data'> <input type='file' name='file' accept='image/*'> <br> <input type='text' value=''> <input type='submit' value='上傳' class='btn btn-success'></form>[[${filename}]]<br><img th:src='http://www.baoyu77737.com/bcjs/@{${filename}}' alt='圖片'></body></html>
(3)TestController.java
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;@Controllerpublic class TestController { /** * 上傳地址 */ @Value('${file.upload.path}') private String filePath; // 跳轉(zhuǎn)上傳頁(yè)面 @RequestMapping('test') public String test() {return 'Page'; } // 執(zhí)行上傳 @RequestMapping('upload') public String upload(@RequestParam('file') MultipartFile file, Model model) {// 獲取上傳文件名String filename = file.getOriginalFilename();// 定義上傳文件保存路徑String path = filePath + 'rotPhoto/';// 新建文件File filepath = new File(path, filename);// 判斷路徑是否存在,如果不存在就創(chuàng)建一個(gè)if (!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs();}try { // 寫(xiě)入文件 file.transferTo(new File(path + File.separator + filename));} catch (IOException e) { e.printStackTrace();}// 將src路徑發(fā)送至html頁(yè)面model.addAttribute('filename', '/images/rotPhoto/' + filename);return 'index'; }}
(4)MyWebAppConfigurer
import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * 資源映射路徑 */@Configurationpublic class MyWebAppConfigurer implements WebMvcConfigurer { /** * 上傳地址 */ @Value('${file.upload.path}') private String filePath; /** * 顯示相對(duì)地址 */ @Value('${file.upload.path.relative}') private String fileRelativePath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(fileRelativePath).addResourceLocations('file:/' + filePath); }}
4 測(cè)試
1 前端ajax
<div class='modal-body'> <form method='post' enctype='multipart/form-data'><input type='file' name='file' id='img'><input type='button' value='上傳' onclick='uploadFile()' style='width: 30%;'> </form></div><script>//上傳文件function uploadFile() { //formData里面存儲(chǔ)的數(shù)據(jù)形式,一對(duì)key/value組成一條數(shù)據(jù),key是唯一的,一個(gè)key可能對(duì)應(yīng)多個(gè)value var myform = new FormData(); // 此時(shí)可以調(diào)用append()方法來(lái)添加數(shù)據(jù) myform.append(’file’, $('#img')[0].files[0]); //驗(yàn)證不為空 var file = $('#img')[0].files[0]; if (file == null) {alert('請(qǐng)選擇文件');return false; } else {$.ajax({ url: '/user/upLoad', type: 'POST', data: myform, async: false, contentType: false, processData: false, success: function (result) {console.log(result);alert('上傳成功!');$('#div_show_img').html('<img id=’input_img’ src=’' + result + '’>');$('#imgPath').attr('value', result);$('#div_upload').removeClass('show'); }, error: function (data) {alert('系統(tǒng)錯(cuò)誤'); }}); }}</script>
2 后端Controller
@ResponseBody@RequestMapping('/upLoad')public String upLoadImage(@RequestParam('file') MultipartFile file) { // 獲取上傳文件名 String filename = file.getOriginalFilename(); String suffixName = filename.substring(filename.lastIndexOf('.')); // 定義上傳文件保存路徑 String path = filePath + 'images/'; //生成新的文件名稱(chēng) String newImgName = UUID.randomUUID().toString() + suffixName; // 新建文件 File filepath = new File(path, newImgName); // 判斷路徑是否存在,如果不存在就創(chuàng)建一個(gè) if (!filepath.getParentFile().exists()) {filepath.getParentFile().mkdirs(); } try {// 寫(xiě)入文件file.transferTo(new File(path + File.separator + newImgName)); } catch (IOException e) {e.printStackTrace(); } return '/images/images/' + newImgName;}
到此這篇關(guān)于Spring Boot 實(shí)現(xiàn)圖片上傳并回顯功能的文章就介紹到這了,更多相關(guān)Spring Boot上傳圖片回顯內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)入門(mén)第四篇(腳本變量、函數(shù)、過(guò)程和條件語(yǔ)句)2. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)3. jscript與vbscript 操作XML元素屬性的代碼4. Jsp servlet驗(yàn)證碼工具類(lèi)分享5. XML在語(yǔ)音合成中的應(yīng)用6. 基于PHP做個(gè)圖片防盜鏈7. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫(xiě)金額)的函數(shù)8. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車(chē)輛管理系統(tǒng)9. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)10. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)
