search
HomeJavajavaTutorialHow SpringBoot+nginx implements resource upload function

1.nginx installation and configuration

The server used by the editor is Alibaba Cloud's lightweight application server, and the system uses Ubuntu. Remember to open the 9090tcp port. If you do not use the 9090 port as the server port, you do not need to use it.

Installation

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

The editor puts the installation package in /usr/nginx, enters the directory and executes tar -zxvf nginx-1.11.3.tar.gz Decompress

Configuration

Modify /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;
 }

This modification should be added. increase, remember not to delete randomly

The last step is to start nginx and execute ./usr/nginx/sbin/nginx

At this point the server nginx is ready

You You can try to download picture 01.jpg in /usr/nginx/image, and then see if the picture can be accessed locally

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工具组件 -->
 <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: 自己服务器ip
 username: 服务器账号
 password: 服务器密码
 port: 22
 rootpath: /usr/nginx/image
 img:
 url: http://ip:9090/  # ftp.img.url 可以不添加,这里只是为了上传文件成功后返回文件路径

Tool class 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服务器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 路径,不存在就创建目录
  * @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 "";
 }
 /**
  * 创建目录
  */
 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();
  }
 }
}

Tool class idutils.class (modify the uploaded image name):

import java.util.random;
public class idutils {
 /**
  * 生成随机图片名
  */
 public static string genimagename() {
  //取当前时间的长整形值包含毫秒
  long millis = system.currenttimemillis();
  //加上三位随机数
  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生成文件在服务器端存储的子目录
  string filepath = new datetime().tostring("/yyyymmdd/");
  //2、把图片上传到图片服务器
  //2.1获取上传的io流
  inputstream input = null;
  try {
   input = uploadfile.getinputstream();
  } catch (ioexception e) {
   e.printstacktrace();
  }
  //2.2调用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("任务结束,共耗时:[" + (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("任务结束,共耗时:[" + (end-begin) + "]毫秒");
  return map;
 }
}

Start the project, a wave of postman artifacts

How SpringBoot+nginx implements resource upload function

How SpringBoot+nginx implements resource upload function

Note:

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

2. The uploads interface of the above code is to implement multiple file uploads

The above is the detailed content of How SpringBoot+nginx implements resource upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment