SpringBoot實(shí)現(xiàn)文件上傳接口
摘要
公司都是采用SpringBoot作為項(xiàng)目框架,其實(shí)SpringBoot和SSM框架很接近,基本上只是將SSM的一些配置項(xiàng)修改為自動(dòng)配置或者簡單的注解配置就可以了,建議不了解的SpringBoot的朋友們可以了解一下,上手很快,其實(shí)文件上傳框架根本沒有多大關(guān)系。我只是順便幫SpringBoot打個(gè)廣告罷了。
正題
需求:需要實(shí)現(xiàn)一個(gè)文件上傳的web接口。
1、先實(shí)現(xiàn)一個(gè)Controller接口,如下:
package com.lanxuewei.utils.aspect;
import com.lanxuewei.utils.interceptor.annotation.AppIdAuthorization;
import com.lanxuewei.utils.model.ReturnCodeAndMsgEnum;
import com.lanxuewei.utils.model.ReturnValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* @author lanxuewei Create in 2018/7/3 20:01
* Description: aop 測(cè)試控制器
*/
@RestController
@RequestMapping(value = "/aop")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testService;
/**
* 文件上傳測(cè)試接口
* @return
*/
@AppIdAuthorization
@RequestMapping("/upload")
public ReturnValue uploadFileTest(@RequestParam("uploadFile") MultipartFile zipFile) {
return testService.uploadFileTest(zipFile);
}
}
2、Service接口如下:
package com.lanxuewei.utils.aspect;
import org.springframework.web.multipart.MultipartFile;
import com.lanxuewei.utils.model.ReturnValue;
public interface TestService {
public ReturnValue uploadFileTest(MultipartFile zipFile);
}
3、Service實(shí)現(xiàn)如下:
package com.lanxuewei.utils.aspect;
import com.lanxuewei.utils.model.ReturnCodeAndMsgEnum;
import com.lanxuewei.utils.model.ReturnValue;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
/**
* @author lanxuewei Create in 2018/8/14 10:01
* Description:
*/
@Service
public class TestServiceImp implements TestService {
private static final Logger logger = LoggerFactory.getLogger(TestServiceImp.class);
@Override
public ReturnValue uploadFileTest(MultipartFile zipFile) {
String targetFilePath = "D:\\test\\uploadTest";
String fileName = UUID.randomUUID().toString().replace("-", "");
File targetFile = new File(targetFilePath + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(targetFile);
IOUtils.copy(zipFile.getInputStream(), fileOutputStream);
logger.info("------>>>>>>uploaded a file successfully!<<<<<<------");
} catch (IOException e) {
return new ReturnValue<>(-1, null);
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
logger.error("", e);
}
}
return new ReturnValue<>(ReturnCodeAndMsgEnum.Success, null);
}
}
說明:
1、targetFilePath為文件保存路徑,本人用于測(cè)試所以指定路徑,可根據(jù)實(shí)際情況進(jìn)行修改。
2、fileName采用UUID生成,保證文件名唯一不重復(fù),但是沒有保留原文件后綴,可通過獲取原文件文件名后,調(diào)用lastIndexOf(“.”)獲取文件原后綴加上。
3、IOUtils為org.apache.commons.io.IOUtils,注意別導(dǎo)入錯(cuò)誤。
4、本文中采用logback日志系統(tǒng),可根據(jù)實(shí)際情況修改或刪除。
附上ReturnValue以及ReturnCodeAndMsgEnum類,用于Controller層統(tǒng)一返回前端的model,如下:
package com.lanxuewei.utils.model;
import java.io.Serializable;
/**
* @author lanxuewei Create in 2018/7/3 20:05
* Description: 統(tǒng)一web返回結(jié)果
*/
public class ReturnValue<T> implements Serializable {
private static final long serialVersionUID = -1959544190118740608L;
private int ret;
private String msg;
private T data;
public ReturnValue() {
this.ret = 0;
this.msg = "";
this.data = null;
}
public ReturnValue(int retCode, String msg, T data) {
this.ret = 0;
this.msg = "";
this.data = null;
this.ret = retCode;
this.data = data;
this.msg = msg;
}
public ReturnValue(int retCode, String msg) {
this.ret = 0;
this.msg = "";
this.data = null;
this.ret = retCode;
this.msg = msg;
}
public ReturnValue(ReturnCodeAndMsgEnum codeAndMsg) {
this(codeAndMsg.getCode(), codeAndMsg.getMsg(), null);
}
public ReturnValue(ReturnCodeAndMsgEnum codeAndMsg, T data) {
this(codeAndMsg.getCode(), codeAndMsg.getMsg(), data);
}
public int getRet() {
return this.ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "ReturnValue{" +
"ret=" + ret +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
package com.lanxuewei.utils.model;
/**
* @author lanxuewei Create in 2018/7/3 20:06
* Description: web相關(guān)接口返回狀態(tài)枚舉
*/
public enum ReturnCodeAndMsgEnum {
Success(0, "ok"),
No_Data(-1, "no data"),
SYSTEM_ERROR(10004, "system error");
private String msg;
private int code;
private ReturnCodeAndMsgEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ReturnCodeAndMsgEnum getByCode(int code) {
ReturnCodeAndMsgEnum[] var1 = values();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
ReturnCodeAndMsgEnum aiTypeEnum = var1[var3];
if (aiTypeEnum.code == code) {
return aiTypeEnum;
}
}
return Success;
}
public String getMsg() {
return this.msg;
}
public int getCode() {
return this.code;
}
}
Postman發(fā)請(qǐng)求返回結(jié)果成功,以上代碼只需要uploadFile一個(gè)參數(shù)即可。

注意事項(xiàng): application.properties配置文件中可以配置文件上傳相關(guān)屬性,配置上傳文件大小限制。
單個(gè)文件最大限制:spring.servlet.multipart.max-file-size=50Mb
單次請(qǐng)求最大限制:spring.servlet.multipart.max-request-size=70Mb
總結(jié):本文功能較為簡單,所以有些過程并沒有更細(xì)致過程以及規(guī)范代碼,比如存放路徑采用項(xiàng)目路徑,新文件名保持和原文件后綴一致等,需要的小伙伴可以根據(jù)自己業(yè)務(wù)進(jìn)行修改。
續(xù)更,總覺得代碼過于隨意了,補(bǔ)充文件上傳獲得文件后綴相關(guān)函數(shù)
private String getFileSuffix(MultipartFile file) {
if (file == null) {
return null;
}
String fileName = file.getOriginalFilename();
int suffixIndex = fileName.lastIndexOf(".");
if (suffixIndex == -1) { // 無后綴
return null;
} else { // 存在后綴
return fileName.substring(suffixIndex, fileName.length());
}
}
在隨機(jī)生成文件名后補(bǔ)充如下代碼即可,如果返回文件后綴不為空則將其加入新產(chǎn)生的文件名中即可:
String fileSuffix = getFileSuffix(zipFile);
if (fileSuffix != null) { // 拼接后綴
fileName += fileSuffix;
}
File targetFile = new File(targetFilePath + File.separator + fileName);
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot Websocket Stomp 消息訂閱推送
本文主要介紹了Springboot Websocket Stomp 消息訂閱推送,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07
java數(shù)據(jù)結(jié)構(gòu)ArrayList詳解
本文詳細(xì)講解了java數(shù)據(jù)結(jié)構(gòu)ArrayList的用法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
spring boot 3.3.0和mybatis plus 3.5.6版本沖突
這篇文章主要介紹了spring boot 3.3.0和mybatis plus 3.5.6版本沖突的問題解決,文中介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
Java實(shí)現(xiàn)郵件發(fā)送QQ郵箱帶附件
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)郵件發(fā)送QQ郵箱帶附件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
淺談SpringBoot實(shí)現(xiàn)自動(dòng)裝配的方法原理
SpringBoot的自動(dòng)裝配是它的一大特點(diǎn),可以大大提高開發(fā)效率,減少重復(fù)性代碼的編寫。本文將詳細(xì)講解SpringBoot如何實(shí)現(xiàn)自動(dòng)裝配,需要的朋友可以參考下2023-05-05

