SpringBoot實(shí)現(xiàn)文件上傳接口

摘要

公司主營(yíng)業(yè)務(wù):成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、移動(dòng)網(wǎng)站開(kāi)發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。創(chuàng)新互聯(lián)建站是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開(kāi)放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。創(chuàng)新互聯(lián)建站推出普洱免費(fèi)做網(wǎng)站回饋大家。

公司都是采用SpringBoot作為項(xiàng)目框架,其實(shí)SpringBoot和SSM框架很接近,基本上只是將SSM的一些配置項(xiàng)修改為自動(dòng)配置或者簡(jiǎn)單的注解配置就可以了,建議不了解的SpringBoot的朋友們可以了解一下,上手很快,其實(shí)文件上傳框架根本沒(méi)有多大關(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);
 }
}

說(shuō)明:

1、targetFilePath為文件保存路徑,本人用于測(cè)試所以指定路徑,可根據(jù)實(shí)際情況進(jìn)行修改。
2、fileName采用UUID生成,保證文件名唯一不重復(fù),但是沒(méi)有保留原文件后綴,可通過(guò)獲取原文件文件名后,調(diào)用lastIndexOf(“.”)獲取文件原后綴加上。
3、IOUtils為org.apache.commons.io.IOUtils,注意別導(dǎo)入錯(cuò)誤。
4、本文中采用logback日志系統(tǒng),可根據(jù)實(shí)際情況修改或刪除。

附上ReturnValue以及ReturnCodeAndMsgEnum類(lèi),用于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ù)即可。

SpringBoot實(shí)現(xiàn)文件上傳接口

注意事項(xiàng): application.properties配置文件中可以配置文件上傳相關(guān)屬性,配置上傳文件大小限制。
單個(gè)文件最大限制:spring.servlet.multipart.max-file-size=50Mb
單次請(qǐng)求最大限制:spring.servlet.multipart.max-request-size=70Mb

總結(jié):本文功能較為簡(jiǎn)單,所以有些過(guò)程并沒(méi)有更細(xì)致過(guò)程以及規(guī)范代碼,比如存放路徑采用項(xiàng)目路徑,新文件名保持和原文件后綴一致等,需要的小伙伴可以根據(jù)自己業(yè)務(wù)進(jìn)行修改。

續(xù)更,總覺(jué)得代碼過(guò)于隨意了,補(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) { // 無(wú)后綴
  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);

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

新聞標(biāo)題:SpringBoot實(shí)現(xiàn)文件上傳接口
網(wǎng)頁(yè)鏈接:http://bm7419.com/article46/jdgphg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、做網(wǎng)站、域名注冊(cè)、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、網(wǎng)站營(yíng)銷(xiāo)、企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名