介紹
這里是小編成長之路的歷程,也是小編的學(xué)習(xí)之路。希望和各位大佬們一起成長!
以下為小編最喜歡的兩句話:
要有最樸素的生活和最遙遠(yuǎn)的夢想,即使明天天寒地凍,山高水遠(yuǎn),路遠(yuǎn)馬亡。
一個(gè)人為什么要努力? 我見過最好的答案就是:因?yàn)槲蚁矚g的東西都很貴,我想去的地方都很遠(yuǎn),我愛的人超完美。因此,小編想說:共勉!?
目錄
前言
一、文件上傳與下載
1、文件上傳
第一步:pom.xml
第三步:在全局配置文件中添加文件上傳的相關(guān)配置
第四步:進(jìn)行文件上傳處理,實(shí)現(xiàn)文件上傳功能
二、回顯圖片
第一步:創(chuàng)建并編寫圖片回顯頁面
三、文件下載
第一步:添加文件下載依賴
第二步:創(chuàng)建文件下載頁面
第三步:創(chuàng)建控制器
一、文件上傳與下載
? 在開發(fā)Web應(yīng)用時(shí),文件上傳和下載是很常見的一個(gè)需求。瀏覽器通過表單形式將文件以流的形式傳遞給服務(wù)器,服務(wù)器再對上傳的數(shù)據(jù)進(jìn)行解析處理。下載文件通過 IO 流實(shí)現(xiàn),大多數(shù)框架并沒有對文件下載進(jìn)行封裝處理,并且文件下載時(shí)涉及不同瀏覽器的解析處理,可能會(huì)出現(xiàn)中文亂碼的情況。
1、文件上傳
實(shí)現(xiàn)文件上傳,需要滿足三個(gè)條件。1、表單提交方式必須是 POST
2、表單需要設(shè)置 enctype 屬性,且值為 multipart/form-data
3、表單需要設(shè)置一個(gè)文件域,也就是表單項(xiàng) type = "file"
第一步:pom.xml
注意:SpringBoot并沒有提供文件上傳所需要的 jar 包或依賴,需要再項(xiàng)目中加入文件上傳的相關(guān) jar 包或 maven 依賴,如圖所示:
?下面是依賴包:
(注意:看你創(chuàng)建的springboot項(xiàng)目是什么版本的,如果你jdk使用的是1.8,那么創(chuàng)建項(xiàng)目的時(shí)候就要選擇2.7.8或者2.7.9,這個(gè)時(shí)候使用下面的依賴版本是沒有沖突的,因?yàn)樾【幰彩鞘褂玫?.7.8,如果使用3及3以上的版本出現(xiàn)問題的話,可以考慮是不是包沖突了)
<!--文件上傳-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
第二步: 編寫文件上傳的表單頁面
在項(xiàng)目中的 resources/templates 目錄創(chuàng)建一個(gè)名為 upload.html 頁面
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
??? <div>
??????? <label>選擇文件:</label>
??????? <input type="file" name="attach"/>
??? </div>
??? <div style="margin-top:20px">
??????? <input type="submit" value="確認(rèn)上傳"/>
??? </div>
</form>
第三步:在全局配置文件中添加文件上傳的相關(guān)配置
application.properties
#設(shè)置單個(gè)文件大小
spring.servlet.multipart.max-file-size=50MB
#設(shè)置總上傳數(shù)據(jù)大小
spring.servlet.multipart.max-request-size=50MB
#自定義屬性
#設(shè)置文件上傳位置(絕對路徑)
file.upload.path=d:/
#設(shè)置文件上傳后回顯位置(相對路徑)
file.upload.path.relative=/**
# 這是連接數(shù)據(jù)庫8.0及以上的版本,如果是5版本就不需要加cj,在url中不需要加時(shí)區(qū),8版本不加時(shí)區(qū)的話
# 可能會(huì)報(bào)時(shí)區(qū)的問題
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
datasource.url= localhost:3306/testdb
spring.datasource.url= jdbc:mysql://${datasource.url}?
useSSL=false&useUnicode=true&characterEncoding=utf-
8&allowMultiQueries=true&autoReconnect=true&maxReconnects=10&serverTimezone=UTC
spring.datasource.username= root
spring.datasource.password= root
需要注意的是,通過 spring.servlet.multipart.max-file-size 屬性設(shè)置單個(gè)上傳文件的大小限制,默認(rèn)1MB,通過spring.servlet.multipart.max-request-size 屬性設(shè)置所有上傳文件的大小限制,默認(rèn)為 10MB。開發(fā)過程中,需要結(jié)合實(shí)際需求合理設(shè)置文件大小。
第四步:進(jìn)行文件上傳處理,實(shí)現(xiàn)文件上傳功能
在 controller 包下創(chuàng)建控制器
package com.lyn.controller;
import org.apache.commons.io.FilenameUtils;
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.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller
public class FileController{
??? // 文件上傳位置
??? @Value("${file.upload.path}")
??? private String filePath;
??? /**
???? * 向文件上傳頁面跳轉(zhuǎn)
???? * @return
???? */
??? @RequestMapping("/toUpload")
??? public String toUpload(){
??????? return "upload";
??? }
??? /**
???? * 文件上傳
???? * @param attach
???? * @param model
???? * @return
???? */
??? @RequestMapping("/upload")
??? public String upload(MultipartFile attach, Model model){
??????? // 判斷文件是否為空,不為空則進(jìn)行文件上傳
??????? if(!attach.isEmpty()){
??????????? // 獲取源文件名稱
??????????? String fileName = attach.getOriginalFilename();
??????????? // 獲取源文件后綴名
??????????? String suffix = FilenameUtils.getExtension(fileName);
??????????? // 使用UUID重命名文件名稱
??????????? String newFileName = UUID.randomUUID().toString().replace("-","")+(".")+suffix;
??????????? // 使用日期解決同一文件夾中文件過多問題(以當(dāng)前日期命名文件夾)
??????????? String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
??????????? // 組裝最終文件名
??????????? String finalName = datePath+"/"+newFileName;
??????????? // 構(gòu)建文件對象
??????????? File dest = new File(filePath + finalName);
??????????? // 判斷該文件夾是否存在,不存在則創(chuàng)建
??????????? if(!dest.getParentFile().exists()){
??????????????? dest.getParentFile().mkdirs(); // 創(chuàng)建文件夾
??????????? }
??????????? try{
??????????????? // 將文件保存到硬盤
??????????????? attach.transferTo(dest);
??????????????? // 將當(dāng)前圖片放到模型中,便于頁面回顯
??????????????? model.addAttribute("image",finalName);
??????????? }catch(IOException e){
??????????????? e.printStackTrace();
??????????? }
??????? }
??????? // 返回頁面(該頁面是templates目錄下的頁面)
????? ??return "show";
??? }
}
第五步:測試
http://localhost:8080/toUpload
二、回顯圖片
如果上傳的文件是圖片,且需要在頁面中將圖片顯示,則需要對圖片進(jìn)行數(shù)據(jù)回顯,需要完成兩個(gè)步驟,分別是:
第一步:創(chuàng)建并編寫圖片回顯頁面
在項(xiàng)目中的 resources/templates 目錄下創(chuàng)建 show.html 頁面,代碼如下所示:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
??? <meta charset="UTF-8">
??? <title>圖片回顯</title>
</head>
<body>
??? <img th:src="@{'/'+${image}}"/>
</body>
</html>
創(chuàng)建并編寫文件上傳配置類
第二步:在項(xiàng)目中的 config 包下新建 UploadConfig 類
package com.lyn.config;
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;
@Configuration
public class UploadConfig implements WebMvcConfigurer {
??? // 上傳地址
??? @Value("${file.upload.path}")
??? private String filePath;
??? // 顯示相對地址
??? @Value("${file.upload.path.relative}")
??? private String fileRelativePath;
//地址映射 url地址與本地磁盤地址映射
??? @Override
??? public void addResourceHandlers(ResourceHandlerRegistry registry){
??????? // 讀取本地文件需要加上 file:/????
??? registry.addResourceHandler(fileRelativePath).addResourceLocations("file:/"+filePath);
??? }
}
三、文件下載
在Web開發(fā)中,文件下載能夠通過IO流實(shí)現(xiàn),所以多數(shù)框架并沒有對文件下載進(jìn)行封裝處理。文件下載時(shí)涉及不同瀏覽器的解析處理,可能會(huì)出現(xiàn)中文亂碼情況,并且不同瀏覽器之間的解析處理方式也會(huì)有所不同,例如谷歌和IE瀏覽器。
第一步:添加文件下載依賴
在 pom.xml 文件中引入文件下載的工具依賴 commons-io,還是需要注意版本的兼容性
<dependency>
??? <groupId>commons-io</groupId>
??? <artifactId>commons-io</artifactId>
??? <version>2.6</version>
</dependency>
第二步:創(chuàng)建文件下載頁面
在 resuources/templates 目錄下創(chuàng)建 download.html 頁面,代碼如下:
<h2>文件下載</h2>
<!-- 注意:這個(gè)路徑是你自己上傳文件的文件夾,比如小編的就在d盤有一個(gè)2023-02-20的文件夾-->
<a th:href="@{2023-02-20/1.jpg}" download="1.jpg">html頁面下載</a>
</body>
如圖:
?
第三步:創(chuàng)建控制器
將方法寫在文件上傳的controller中文章來源:http://www.zghlxwxcb.cn/news/detail-791744.html
/**
* 文件下載的兩種方式,使用其中一種下載即可
*/
@RequestMapping("/download")
public String downLoad(){
return "download";
}
@GetMapping("/t3")
public ResponseEntity<ByteArrayResource> down3() throws Exception {
byte[] bytes = Files.readAllBytes(new File("d:\\2023-02-20\\1.jpg").toPath());
ByteArrayResource bar = new ByteArrayResource(bytes);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-disposition", "attachment; filename=1.jpg")
.body(bar);
}
以上就是小編所寫得文件上傳,回顯圖片,以及文件下載,希望能夠幫助到大家!!謝謝各位大佬的觀看?。?span toymoban-style="hidden">文章來源地址http://www.zghlxwxcb.cn/news/detail-791744.html
到了這里,關(guān)于【SpringBoot】簡單的文件上傳和文件下載以及圖片回顯的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!