溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于SpringBoot如何實(shí)現(xiàn)圖片上傳與顯示

發(fā)布時(shí)間:2021-05-24 11:44:07 來源:億速云 閱讀:3248 作者:小新 欄目:編程語言

小編給大家分享一下基于SpringBoot如何實(shí)現(xiàn)圖片上傳與顯示,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

SpringBoot實(shí)現(xiàn)圖片上傳與顯示:

效果圖預(yù)覽

基于SpringBoot如何實(shí)現(xiàn)圖片上傳與顯示

思路

  • 一般情況下都是將用戶上傳的圖片放到服務(wù)器的某個(gè)文件夾中,然后將圖片在服務(wù)器中的路徑存入數(shù)據(jù)庫。本Demo也是這樣做的。

  • 由于用戶自己保存的圖片文件名可能跟其他用戶同名造成沖突,因此本Demo選擇了使用UUID來生成隨機(jī)的文件名解決沖突。

  • 但是本Demo不涉及任何有關(guān)數(shù)據(jù)庫的操作,便于演示,就用原來的文件名。

步驟

pom相關(guān)依賴

  • 基于Spring boot當(dāng)然是繼承了spring boot這不用多說

  • 具體依賴,主要是FreeMarker相關(guān)依賴為了展現(xiàn)頁面,習(xí)慣用JSP也可以添加JSP的依賴,只是為了展示頁面,這個(gè)不重要。

<dependencies>
 <!--FreeMarker模板視圖依賴-->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
</dependencies>

application.properties相關(guān)配置

除了視圖模板相關(guān)的配置,重點(diǎn)是要配置一下文件上傳的內(nèi)存大小和文件上傳路徑

server.port=8102

### 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
#設(shè)置面板后綴
spring.freemarker.suffix=.ftl

# 設(shè)置單個(gè)文件最大內(nèi)存
multipart.maxFileSize=50Mb
# 設(shè)置所有文件最大內(nèi)存
multipart.maxRequestSize=50Mb
# 自定義文件上傳路徑
web.upload-path=E:/Develop/Files/Photos/

生成文件名

不準(zhǔn)備生成文件名的可以略過此步驟

package com.wu.demo.fileupload.demo.util;

public class FileNameUtils {

 /**
  * 獲取文件后綴
  * @param fileName
  * @return
  */
 public static String getSuffix(String fileName){
  return fileName.substring(fileName.lastIndexOf("."));
 }

 /**
  * 生成新的文件名
  * @param fileOriginName 源文件名
  * @return
  */
 public static String getFileName(String fileOriginName){
  return UUIDUtils.getUUID() + FileNameUtils.getSuffix(fileOriginName);
 }

}
import java.util.UUID;

/**
 * 生成文件名
 */
public class UUIDUtils {

 public static String getUUID(){
  return UUID.randomUUID().toString().replace("-", "");
 }

}

文件上傳工具類

package com.wu.demo.fileupload.demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上傳工具包
 */
public class FileUtils {

 /**
  *
  * @param file 文件
  * @param path 文件存放路徑
  * @param fileName 源文件名
  * @return
  */
 public static boolean upload(MultipartFile file, String path, String fileName){

  // 生成新的文件名
  //String realPath = path + "/" + FileNameUtils.getFileName(fileName);

  //使用原文件名
  String realPath = path + "/" + fileName;

  File dest = new File(realPath);

  //判斷文件父目錄是否存在
  if(!dest.getParentFile().exists()){
   dest.getParentFile().mkdir();
  }

  try {
   //保存文件
   file.transferTo(dest);
   return true;
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  }

 }
}

Controller

package com.wu.demo.fileupload.demo.controller;

import com.wu.demo.fileupload.demo.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class TestController {

 private final ResourceLoader resourceLoader;

 @Autowired
 public TestController(ResourceLoader resourceLoader) {
  this.resourceLoader = resourceLoader;
 }

 @Value("${web.upload-path}")
 private String path;

 /**
  * 跳轉(zhuǎn)到文件上傳頁面
  * @return
  */
 @RequestMapping("test")
 public String toUpload(){
  return "test";
 }

 /**
  *
  * @param file 要上傳的文件
  * @return
  */
 @RequestMapping("fileUpload")
 public String upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){

  // 要上傳的目標(biāo)文件存放路徑
  String localPath = "E:/Develop/Files/Photos";
  // 上傳成功或者失敗的提示
  String msg = "";

  if (FileUtils.upload(file, localPath, file.getOriginalFilename())){
   // 上傳成功,給出頁面提示
   msg = "上傳成功!";
  }else {
   msg = "上傳失??!";

  }

  // 顯示圖片
  map.put("msg", msg);
  map.put("fileName", file.getOriginalFilename());

  return "forward:/test";
 }

 /**
  * 顯示單張圖片
  * @return
  */
 @RequestMapping("show")
 public ResponseEntity showPhotos(String fileName){

  try {
   // 由于是讀取本機(jī)的文件,file是一定要加上的, path是在application配置文件中的路徑
   return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
  } catch (Exception e) {
   return ResponseEntity.notFound().build();
  }
 }

}

頁面

頁面主要是from表單和下面的 <img src="/show?fileName=${fileName}" /> ,其余都是細(xì)節(jié)。

<!DOCTYPE html>
<head>
 <meta charset="UTF-8" />
 <title>圖片上傳Demo</title>
</head>
<body>
<h2 >圖片上傳Demo</h2>
<form action="fileUpload" method="post" enctype="multipart/form-data">
 <p>選擇文件: <input type="file" name="fileName"/></p>
 <p><input type="submit" value="提交"/></p>
</form>
<#--判斷是否上傳文件-->
<#if msg??>
 <span>${msg}</span><br>
<#else >
 <span>${msg!("文件未上傳")}</span><br>
</#if>
<#--顯示圖片,一定要在img中的src發(fā)請(qǐng)求給controller,否則直接跳轉(zhuǎn)是亂碼-->
<#if fileName??>
<img src="/show?fileName=${fileName}" />
<#else>
<img src="/show" />
</#if>
</body>
</html>

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個(gè)服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

看完了這篇文章,相信你對(duì)“基于SpringBoot如何實(shí)現(xiàn)圖片上傳與顯示”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI