佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > 實(shí)例詳解SpringBoot+nginx實(shí)現(xiàn)資源上傳功能

實(shí)例詳解SpringBoot+nginx實(shí)現(xiàn)資源上傳功能

熱門標(biāo)簽:檢查注冊(cè)表項(xiàng) 網(wǎng)站建設(shè) 使用U盤裝系統(tǒng) 百度競(jìng)價(jià)點(diǎn)擊價(jià)格的計(jì)算公式 硅谷的囚徒呼叫中心 智能手機(jī) 阿里云 美圖手機(jī)

最近小編在學(xué)習(xí)使用nginx放置靜態(tài)資源,例如圖片、視頻、css/js等,下面就來(lái)記錄一下一波學(xué)習(xí)干貨。

1.nginx安裝及配置

小編使用的服務(wù)器是阿里云的輕量應(yīng)用服務(wù)器,系統(tǒng)使用的是Ubuntu。注意記得開(kāi)放 9090TCP端口,如果不使用 9090端口作為服務(wù)器端口也可不用。

安裝

首先,獲取安裝包是必要的吧,這里提供一個(gè)nginx-1.11.3-ubuntu.tar.gz https://pan.baidu.com/s/1vvb41QkOJ4VqfyFckXBkjA (密碼45wz)

小編是將安裝包放在/usr/nginx 中,進(jìn)入目錄下然后執(zhí)行 tar -zxvf nginx-1.11.3.tar.gz 進(jìn)行解壓

配置

修改 /usr/nginx/conf/nginx.conf :

server {
 listen  9090;
 server_name localhost;

 location ~ .(jpg|png|jpeg|gif|bmp)$ { #可識(shí)別的文件后綴
 root /usr/nginx/image/; #圖片的映射路徑
  autoindex on; #開(kāi)啟自動(dòng)索引
 expires 1h; #過(guò)期時(shí)間
 }
 location ~ .(css|js)$ {
  root /usr/nginx/static/;
  autoindex on;
  expires 1h;
 } 
 location ~ .(AVI|mov|rmvb|rm|FLV|mp4|3GP)$ {
  root /usr/nginx/video/;
  autoindex on;
  expires 1h;
 }

該修改的修改,該增加的增加,切記勿亂刪

最后一步,啟動(dòng)nginx,執(zhí)行 ./usr/nginx/sbin/nginx

到這里服務(wù)器nginx就準(zhǔn)備可以了

你可以試下在 /usr/nginx/image 下放圖片01.jpg,然后在本地 http://ip:9090/01.jpg 看看圖片能否訪問(wèn)到

2. SpringBoot 實(shí)現(xiàn)資源的上傳

pom.xml:

<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.7.RELEASE</version>
</parent>
<dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.1.7.RELEASE</version>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <version>2.1.7.RELEASE</version>
  <scope>test</scope>
 </dependency>
 <!-- Apache工具組件 -->
 <dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.8.1</version>
 </dependency>
 <dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.3.2</version>
 </dependency>
 <dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.6</version>
 </dependency>
 <!-- 文件上傳組件 -->
 <dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
 </dependency>
 <dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.22</version>
 </dependency>
 <dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.54</version>
 </dependency>
 <dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
  <version>2.10.3</version>
 </dependency>
</dependencies>

appilcation.yml:

ftp:
 host: 自己服務(wù)器ip
 userName: 服務(wù)器賬號(hào)
 password: 服務(wù)器密碼
 port: 22
 rootPath: /usr/nginx/image
 img:
 url: http://ip:9090/  # ftp.img.url 可以不添加,這里只是為了上傳文件成功后返回文件路徑

工具類 FtpUtil.class:

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.util.Properties;
@Component
public class FtpUtil {
 private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);
 /**
  * ftp服務(wù)器ip地址
  */
 private static String host;
 @Value("${ftp.host}")
 public void setHost(String val){
  FtpUtil.host = val;
 }
 /**
  * 端口
  */
 private static int port;
 @Value("${ftp.port}")
 public void setPort(int val){
  FtpUtil.port = val;
 }
 /**
  * 用戶名
  */
 private static String userName;
 @Value("${ftp.userName}")
 public void setUserName(String val){
  FtpUtil.userName = val;
 }
 /**
  * 密碼
  */
 private static String password;
 @Value("${ftp.password}")
 public void setPassword(String val){
  FtpUtil.password = val;
 }
 /**
  * 存放圖片的根目錄
  */
 private static String rootPath;
 @Value("${ftp.rootPath}")
 public void setRootPath(String val){
  FtpUtil.rootPath = val;
 }
 /**
  * 存放圖片的路徑
  */
 private static String imgUrl;
 @Value("${ftp.img.url}")
 public void setImgUrl(String val){
  FtpUtil.imgUrl = val;
 }
 /**
  * 獲取連接
  */
 private static ChannelSftp getChannel() throws Exception{
  JSch jsch = new JSch();
  //->ssh root@host:port
  Session sshSession = jsch.getSession(userName,host,port);
  //密碼
  sshSession.setPassword(password);
  Properties sshConfig = new Properties();
  sshConfig.put("StrictHostKeyChecking", "no");
  sshSession.setConfig(sshConfig);
  sshSession.connect();
  Channel channel = sshSession.openChannel("sftp");
  channel.connect();
  return (ChannelSftp) channel;
 }
 /**
  * ftp上傳圖片
  * @param inputStream 圖片io流
  * @param imagePath 路徑,不存在就創(chuàng)建目錄
  * @param imagesName 圖片名稱
  * @return urlStr 圖片的存放路徑
  */
 public static String putImages(InputStream inputStream, String imagePath, String imagesName){
  try {
   ChannelSftp sftp = getChannel();
   String path = rootPath + imagePath + "/";
   createDir(path,sftp);
   //上傳文件
   sftp.put(inputStream, path + imagesName);
   logger.info("上傳成功!");
   sftp.quit();
   sftp.exit();
   //處理返回的路徑
   String resultFile;
   resultFile = imgUrl + imagePath + imagesName;
   return resultFile;
  } catch (Exception e) {
   logger.error("上傳失?。? + e.getMessage());
  }
  return "";
 }
 /**
  * 創(chuàng)建目錄
  */
 private static void createDir(String path,ChannelSftp sftp) throws SftpException {
  String[] folders = path.split("/");
  sftp.cd("/");
  for ( String folder : folders ) {
   if ( folder.length() > 0 ) {
    try {
     sftp.cd( folder );
    }catch ( SftpException e ) {
     sftp.mkdir( folder );
     sftp.cd( folder );
    }
   }
  }
 }
 /**
  * 刪除圖片
  */
 public static void delImages(String imagesName){
  try {
   ChannelSftp sftp = getChannel();
   String path = rootPath + imagesName;
   sftp.rm(path);
   sftp.quit();
   sftp.exit();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

工具類IDUtils.class(修改上傳圖片名):

import java.util.Random;
public class IDUtils {
 /**
  * 生成隨機(jī)圖片名
  */
 public static String genImageName() {
  //取當(dāng)前時(shí)間的長(zhǎng)整形值包含毫秒
  long millis = System.currentTimeMillis();
  //加上三位隨機(jī)數(shù)
  Random random = new Random();
  int end3 = random.nextInt(999);
  //如果不足三位前面補(bǔ)0
  String str = millis + String.format("%03d", end3);
  return str;
 }
}

NginxService.class:

import com.wzy.util.FtpUtil;
import com.wzy.util.IDUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
/**
 * @Package: com.wzy.service
 * @Author: Clarence1
 * @Date: 2019/10/4 21:34
 */
@Service
@Slf4j
public class NginxService {
 public Object uploadPicture(MultipartFile uploadFile) {
  //1、給上傳的圖片生成新的文件名
  //1.1獲取原始文件名
  String oldName = uploadFile.getOriginalFilename();
  //1.2使用IDUtils工具類生成新的文件名,新文件名 = newName + 文件后綴
  String newName = IDUtils.genImageName();
  assert oldName != null;
  newName = newName + oldName.substring(oldName.lastIndexOf("."));
  //1.3生成文件在服務(wù)器端存儲(chǔ)的子目錄
  String filePath = new DateTime().toString("/yyyyMMdd/");
  //2、把圖片上傳到圖片服務(wù)器
  //2.1獲取上傳的io流
  InputStream input = null;
  try {
   input = uploadFile.getInputStream();
  } catch (IOException e) {
   e.printStackTrace();
  }
  //2.2調(diào)用FtpUtil工具類進(jìn)行上傳
  return FtpUtil.putImages(input, filePath, newName);
 }
}

NginxController.class:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.service.NginxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
@RestController
@Slf4j
public class NginxController {
 @Autowired
 private NginxService nginxService;
 /**
  * 可上傳圖片、視頻,只需在nginx配置中配置可識(shí)別的后綴
  */
 @PostMapping("/upload")
 public String pictureUpload(@RequestParam(value = "file") MultipartFile uploadFile) {
  long begin = System.currentTimeMillis();
  String json = "";
  try {
   Object result = nginxService.uploadPicture(uploadFile);
   json = new ObjectMapper().writeValueAsString(result);
  } catch (JsonProcessingException e) {
   e.printStackTrace();
  }
  long end = System.currentTimeMillis();
  log.info("任務(wù)結(jié)束,共耗時(shí):[" + (end-begin) + "]毫秒");
  return json;
 }
 @PostMapping("/uploads")
 public Object picturesUpload(@RequestParam(value = "file") MultipartFile[] uploadFile) {
  long begin = System.currentTimeMillis();
  Map<Object, Object> map = new HashMap<>(10);
  int count = 0;
  for (MultipartFile file : uploadFile) {
   Object result = nginxService.uploadPicture(file);
   map.put(count, result);
   count++;
  }
  long end = System.currentTimeMillis();
  log.info("任務(wù)結(jié)束,共耗時(shí):[" + (end-begin) + "]毫秒");
  return map;
 }
}

啟動(dòng)項(xiàng)目,Postman神器一波

注意:

1.如果要視頻跟圖片一起上傳的話,只要修改 nginx.conf配置文件,添加相應(yīng)的視頻后綴即可,代碼沒(méi)變,上傳后也是放在 /usr/image 下,要不然文件能上傳,但是訪問(wèn)不了

2.上面代碼 uploads接口是實(shí)現(xiàn)多文件上傳

源碼下載

總結(jié)

以上所述是小編給大家介紹的SpringBoot+nginx實(shí)現(xiàn)資源上傳功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

標(biāo)簽:賀州 懷化 黃山 湘潭 通遼 湖北 山南 煙臺(tái)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《實(shí)例詳解SpringBoot+nginx實(shí)現(xiàn)資源上傳功能》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    新田县| 高清| 巴东县| 肥乡县| 太康县| 定日县| 大宁县| 盱眙县| 包头市| 舟曲县| 巴中市| 常宁市| 靖西县| 庆安县| 广南县| 南召县| 景德镇市| 陇川县| 永顺县| 英吉沙县| 如皋市| 青川县| 翼城县| 平顺县| 岱山县| 广安市| 于田县| 礼泉县| 河北区| 繁峙县| 凌源市| 桐庐县| 平阴县| 福建省| 西贡区| 宿松县| 南宫市| 林周县| 麦盖提县| 岳西县| 琼海市|