欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2019年10月12日 11:29:50   作者:玖、先森  
這篇文章主要介紹了SpringBoot+nginx實現(xiàn)資源上傳功能,由于小編最近在使用nginx放置靜態(tài)資源問題,遇到很多干貨,特此分享到腳本之家平臺,供大家參考,需要的朋友可以參考下

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

1.nginx安裝及配置

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

安裝

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

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

配置

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

server {
 listen  9090;
 server_name localhost;

 location ~ .(jpg|png|jpeg|gif|bmp)$ { #可識別的文件后綴
 root /usr/nginx/image/; #圖片的映射路徑
  autoindex on; #開啟自動索引
 expires 1h; #過期時間
 }
 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;
 }

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

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

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

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

2. SpringBoot 實現(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ù)器賬號
 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 {
 /**
  * 生成隨機圖片名
  */
 public static String genImageName() {
  //取當(dāng)前時間的長整形值包含毫秒
  long millis = System.currentTimeMillis();
  //加上三位隨機數(shù)
  Random random = new Random();
  int end3 = random.nextInt(999);
  //如果不足三位前面補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ù)器端存儲的子目錄
  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工具類進行上傳
  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配置中配置可識別的后綴
  */
 @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é)束,共耗時:[" + (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é)束,共耗時:[" + (end-begin) + "]毫秒");
  return map;
 }
}

啟動項目,Postman神器一波

注意:

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

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

源碼下載

總結(jié)

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

相關(guān)文章

  • Nginx進程管理和重載原理詳解

    Nginx進程管理和重載原理詳解

    這篇文章主要給大家介紹了關(guān)于Nginx進程管理和重載原理的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • nginx環(huán)境下配置ssl加密(單雙向認證、部分https)

    nginx環(huán)境下配置ssl加密(單雙向認證、部分https)

    這篇文章主要介紹了nginx環(huán)境下配置ssl加密(單雙向認證、部分https),具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2016-11-11
  • Nginx設(shè)置靜態(tài)頁面壓縮和緩存過期時間的方法

    Nginx設(shè)置靜態(tài)頁面壓縮和緩存過期時間的方法

    這篇文章主要介紹了Nginx設(shè)置靜態(tài)頁面壓縮和緩存過期時間的方法,也是服務(wù)器架設(shè)后的必備設(shè)置,需要的朋友可以參考下
    2015-07-07
  • nginx實現(xiàn)多geoserver服務(wù)的負載均衡的示例代碼

    nginx實現(xiàn)多geoserver服務(wù)的負載均衡的示例代碼

    本文主要介紹了nginx實現(xiàn)多geoserver服務(wù)的負載均衡的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • 記錄一次nginx啟動失敗的解決過程

    記錄一次nginx啟動失敗的解決過程

    小編最近遇到這樣一個問題docker nginx起不來了,導(dǎo)致jira域名映射失敗,如何解決呢?下面小編給大家分享下nginx啟動失敗的解決過程,感興趣的朋友一起看看吧
    2022-02-02
  • 詳解Nginx的超時keeplive_timeout配置步驟

    詳解Nginx的超時keeplive_timeout配置步驟

    Nginx 處理的每個請求均有相應(yīng)的超時設(shè)置,本文主要介紹了Nginx的超時keeplive_timeout配置步驟,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 淘寶Web服務(wù)器Tengine在CentOS下的安裝教程

    淘寶Web服務(wù)器Tengine在CentOS下的安裝教程

    這篇文章主要介紹了淘寶Web服務(wù)器Tengine在CentOS下的安裝教程,本文同時介紹了Tengine是什么,需要的朋友可以參考下
    2014-07-07
  • Nginx配置二級域名的方法實現(xiàn)

    Nginx配置二級域名的方法實現(xiàn)

    本文主要介紹了Nginx配置二級域名的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • ELK收集Nginx日志的項目實戰(zhàn)

    ELK收集Nginx日志的項目實戰(zhàn)

    本文主要介紹了ELK收集Nginx日志的項目實戰(zhàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 詳解nginx使用ssl模塊配置HTTPS支持

    詳解nginx使用ssl模塊配置HTTPS支持

    本篇文章主要介紹了詳解nginx使用ssl模塊配置HTTPS支持 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-12-12

最新評論