SpringCloud實(shí)現(xiàn)文件上傳功能的方法詳解
圖片上傳
剛才的新增實(shí)現(xiàn)中,我們并沒有上傳圖片,接下來我們一起完成圖片上傳邏輯。
文件的上傳并不只是在品牌管理中有需求,以后的其它服務(wù)也可能需要,因此我們創(chuàng)建一個(gè)獨(dú)立的微服務(wù),專門處理各種上傳。
搭建項(xiàng)目
創(chuàng)建SpringCloud項(xiàng)目
添加依賴
我們需要EurekaClient和web依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-upload</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
編寫配置
server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
max-file-size: 5MB # 限制文件上傳的大小
# Eureka
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
lease-renewal-interval-in-seconds: 5 # 每隔5秒發(fā)送一次心跳
lease-expiration-duration-in-seconds: 10 # 10秒不發(fā)送就過期
prefer-ip-address: true
ip-address: 127.0.0.1
instance-id: ${spring.application.name}:${server.port}需要注意的是,我們應(yīng)該添加了限制文件大小的配置
2.1.4.啟動(dòng)類
@SpringBootApplication
@EnableDiscoveryClient
public class LyUploadService {
public static void main(String[] args) {
SpringApplication.run(LyUploadService.class, args);
}
}
結(jié)構(gòu):

編寫上傳功能
controller
編寫controller需要知道4個(gè)內(nèi)容:
- 請(qǐng)求方式:上傳肯定是POST
- 請(qǐng)求路徑:/upload/image
- 請(qǐng)求參數(shù):文件,參數(shù)名是file,SpringMVC會(huì)封裝為一個(gè)接口:MultipleFile
- 返回結(jié)果:上傳成功后得到的文件的url路徑
代碼如下:
package com.leyou.upload.web;
import com.leyou.upload.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService;
/**
* 上傳圖片功能
* @param file
* @return
*/
@PostMapping("image")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file){
String url = uploadService.uploadImage(file);
if(StringUtils.isBlank(url)){
// url為空,證明上傳失敗
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// 返回200,并且攜帶url路徑
return ResponseEntity.ok(url);
}
}
service
在上傳文件過程中,我們需要對(duì)上傳的內(nèi)容進(jìn)行校驗(yàn):
- 校驗(yàn)文件大小
- 校驗(yàn)文件的媒體類型
- 校驗(yàn)文件的內(nèi)容
文件大小在Spring的配置文件中設(shè)置,因此已經(jīng)會(huì)被校驗(yàn),我們不用管。
具體代碼:
package com.leyou.upload.service;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class UploadService {
private static final List<String> ALLOW_TYPES = Arrays.asList("image/png", "image/jpeg", "image/bmg");
public String uploadImage(MultipartFile file) {
try {
//校驗(yàn)文件類型
String contentType = file.getContentType();
if(!ALLOW_TYPES.contains(contentType)){
throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
}
//校驗(yàn)文件的內(nèi)容
BufferedImage image = ImageIO.read(file.getInputStream());
if(image == null){
throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
}
//準(zhǔn)備目標(biāo)路徑
File dest = new File("E:\黑馬程序員57期\09 微服務(wù)電商【黑馬樂優(yōu)商城】\upload\",file.getOriginalFilename());
file.transferTo(dest);
//返回路徑
return "http://image.leyou.com/"+file.getOriginalFilename();
} catch (IOException e) {
log.error("上傳文件失敗",e);
throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
}
}
}
這里有一個(gè)問題:為什么圖片地址需要使用另外的url?
圖片不能保存在服務(wù)器內(nèi)部,這樣會(huì)對(duì)服務(wù)器產(chǎn)生額外的加載負(fù)擔(dān)
一般靜態(tài)資源都應(yīng)該使用獨(dú)立域名,這樣訪問靜態(tài)資源時(shí)不會(huì)攜帶一些不必要的cookie,減小請(qǐng)求的數(shù)據(jù)量
測(cè)試上傳
我們通過RestClient工具來測(cè)試:

結(jié)果:

去目錄下查看:

上傳成功!
到此這篇關(guān)于SpringCloud實(shí)現(xiàn)文件上傳功能的方法詳解的文章就介紹到這了,更多相關(guān)SpringCloud文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例
這篇文章主要為大家介紹了Java線程的創(chuàng)建介紹及實(shí)現(xiàn)方式示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
MyBatisPlus防全表更新與刪除的實(shí)現(xiàn)示例
本文主要介紹了MyBatisPlus防全表更新與刪除的實(shí)現(xiàn)示例,針對(duì) update 和 delete 語(yǔ)句,阻止惡意的全表更新和全表刪除,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
SpringBoot中@ConfigurationProperties 配置綁定
本文主要介紹了SpringBoot中@ConfigurationProperties 配置綁定,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
JAVA利用HttpClient進(jìn)行HTTPS接口調(diào)用的方法
本篇文章主要介紹了JAVA利用HttpClient進(jìn)行HTTPS接口調(diào)用的方法,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08

