Java工作笔记-Spring Boot上传图片并显示
生活随笔
收集整理的這篇文章主要介紹了
Java工作笔记-Spring Boot上传图片并显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
?
基本概念
代碼與實例
源碼打包下載
?
?
基本概念
這個是基因Github的一個項目改的,因為頁面關閉了,在此找不到了,不能把連接發上來。
這里使用的是FreeMarker。
為了避免重名,使用了UUID生成隨機。
找圖片文件主要是使用ResourceLoader。
?
代碼與實例
程序運行截圖如下:
點擊選擇文件,然后提交:
看看文件夾:
關鍵源碼如下:
application.properties
### FreeMarker 配置 spring.freemarker.allow-request-override=false #Enable template caching.啟用模板緩存。 spring.freemarker.cache=false spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false #設置面板后綴 spring.freemarker.suffix=.ftl# 設置單個文件最大內存 multipart.maxFileSize=50Mb # 設置所有文件最大內存 multipart.maxRequestSize=50Mb # 自定義文件上傳路徑 web.upload-path=F:/SpringTest/TestController.java
package com.example.demo.controller;import com.example.demo.util.FileUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ResourceLoader; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile;import java.util.Map;@Controller public class TestController {private final ResourceLoader resourceLoader;public TestController(ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader;}@Value("${web.upload-path}")private String path;@RequestMapping("test")private String toUpload(){return "test";}//上傳文件@RequestMapping("fileUpload")public String upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){String localPath = "F:/SpringTest";String msg = "";StringBuffer newName = new StringBuffer();if(FileUtils.upload(file, localPath, file.getOriginalFilename(), newName)){msg = "上傳成功";}else{msg = "上傳失敗";}newName.toString();map.put("msg", msg);//map.put("fileName", file.getOriginalFilename());map.put("fileName", newName.toString());return "forward:/test";}//顯示單張圖片@RequestMapping("show")public ResponseEntity showPhotos(String fileName){if(fileName == null){return ResponseEntity.notFound().build();}try{return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));}catch (Exception e){return ResponseEntity.notFound().build();}} }?
?
源碼打包下載
地址如下:
https://github.com/fengfanchen/Java/tree/master/loadPic
總結
以上是生活随笔為你收集整理的Java工作笔记-Spring Boot上传图片并显示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QML工作笔记-使用QML中的Date将
- 下一篇: Qt文档阅读笔记-QWindow的进一步