The example explains in detail that springboot + nginx realizes the resource upload function

Time:2021-8-15

Recently, Xiaobian is learning to use nginx to place static resources, such as pictures, videos, CSS / JS, etc. Let’s record a wave of learning dry goods.

1. Nginx installation and configuration

The server used by Xiaobian is alicloud’s lightweight application server, and the system uses Ubuntu. Note: remember to open the 9090 TCP port. If the 9090 port is not used as the server port, it can also be used.

install

First, it is necessary to obtain the installation package. Here is an nginx-1.11.3-ubuntu.tar.gz https://pan.baidu.com/s/1vvb41QkOJ4VqfyFckXBkjA (password 45wz)

Xiaobian puts the installation package in / usr / nginx, enters the directory, and then executes ittar -zxvf nginx-1.11.3.tar.gz Unzip

to configure

Modify / usr / nginx / conf / nginx.conf:

server {
 listen  9090;
 server_name localhost;

 Location ~. (jpg|png|jpeg|gif|bmp) ${# recognizable file suffix
 root /usr/nginx/image/; # Mapping path of picture
  autoindex on; # Turn on automatic indexing
 expires 1h; # Expiration time
 }
 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;
 }

Remember not to delete the modification and addition of the modification and addition

Finally, start nginx and execute. / usr / nginx / SBIN / nginx

Here, the server nginx is ready

You can try putting picture 01.jpg in / usr / nginx / image, and then put it locally http://ip:9090/01.jpg See if the picture can be accessed

2. Springboot implements resource upload

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 tool components -- >
 <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>
 <!--  File upload component -- >
 <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: server IP
 Username: server account
 Password: server password
 port: 22
 rootPath: /usr/nginx/image
 img:
 url:  http://ip:9090/   #Ftp.img.url can not be added. It is just to return the file path after uploading the file successfully

Tool class ftutil.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 server IP address
  */
 private static String host;
 @Value("${ftp.host}")
 public void setHost(String val){
  FtpUtil.host = val;
 }
 /**
  *Port
  */
 private static int port;
 @Value("${ftp.port}")
 public void setPort(int val){
  FtpUtil.port = val;
 }
 /**
  *User name
  */
 private static String userName;
 @Value("${ftp.userName}")
 public void setUserName(String val){
  FtpUtil.userName = val;
 }
 /**
  *Code
  */
 private static String password;
 @Value("${ftp.password}")
 public void setPassword(String val){
  FtpUtil.password = val;
 }
 /**
  *The root directory where the pictures are stored
  */
 private static String rootPath;
 @Value("${ftp.rootPath}")
 public void setRootPath(String val){
  FtpUtil.rootPath = val;
 }
 /**
  *Path to store pictures
  */
 private static String imgUrl;
 @Value("${ftp.img.url}")
 public void setImgUrl(String val){
  FtpUtil.imgUrl = val;
 }
 /**
  *Get connection
  */
 private static ChannelSftp getChannel() throws Exception{
  JSch jsch = new JSch();
  //->ssh [email protected]:port
  Session sshSession = jsch.getSession(userName,host,port);
  //Code
  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 upload picture
  *@ param InputStream picture IO stream
  *@ param imagepath path, create directory if it does not exist
  *@ param imagesname picture name
  *@ return urlstr the storage path of the picture
  */
 public static String putImages(InputStream inputStream, String imagePath, String imagesName){
  try {
   ChannelSftp sftp = getChannel();
   String path = rootPath + imagePath + "/";
   createDir(path,sftp);
   //Upload file
   sftp.put(inputStream, path + imagesName);
   Logger.info ("upload succeeded!");
   sftp.quit();
   sftp.exit();
   //Path returned by processing
   String resultFile;
   resultFile = imgUrl + imagePath + imagesName;
   return resultFile;
  } catch (Exception e) {
   Logger. Error ("upload failed:" + e.getmessage());
  }
  return "";
 }
 /**
  *Create directory
  */
 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 );
    }
   }
  }
 }
 /**
  *Delete picture
  */
 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();
  }
 }
}

Tool class idutils.class (modify uploaded picture name):

import java.util.Random;
public class IDUtils {
 /**
  *Generate random picture name
  */
 public static String genImageName() {
  //Take the long integer value of the current time, including milliseconds
  long millis = System.currentTimeMillis();
  //Add three random numbers
  Random random = new Random();
  int end3 = random.nextInt(999);
  //If there are less than three digits, fill 0 in front
  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. Generate a new file name for the uploaded image
  //1.1 get the original file name
  String oldName = uploadFile.getOriginalFilename();
  //1.2 use the idutils tool class to generate a new file name. The new file name = newname + file suffix
  String newName = IDUtils.genImageName();
  assert oldName != null;
  newName = newName + oldName.substring(oldName.lastIndexOf("."));
  //1.3 subdirectories of generated files stored on the server side
  String filePath = new DateTime().toString("/yyyyMMdd/");
  //2. Upload the picture to the picture server
  //2.1 get the uploaded IO stream
  InputStream input = null;
  try {
   input = uploadFile.getInputStream();
  } catch (IOException e) {
   e.printStackTrace();
  }
  //2.2 call the ftutil tool class to upload
  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;
 /**
  *Pictures and videos can be uploaded. You only need to configure recognizable suffixes in nginx configuration
  */
 @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 ("task end, total elapsed time: [" + (end begin) + "] MS");
  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 ("task end, total elapsed time: [" + (end begin) + "] MS");
  return map;
 }
}

Start the project, postman artifact wave

be careful:

1. If you want to upload the video together with the picture, just modify the nginx.conf configuration file and add the corresponding video suffix. The code has not changed. After uploading, it is also placed under / usr / image. Otherwise, the file can be uploaded, but it cannot be accessed

2. The uploads interface in the above code is used to upload multiple files

Source download

summary

The above is what Xiaobian introduced to you. Springboot + nginx realizes the resource upload function. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!