Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use nginx to realize resource upload function in SpringBoot

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

How to use nginx to upload resources in SpringBoot? Many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can gain something.

Configuration

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/; # the mapping path of the picture autoindex on; # enables automatic indexing of 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;}

The modification of the modification, the addition of the increase, do not delete it indiscriminately

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

Here, the server nginx is ready.

You can try downloading the picture 01.jpg in / usr/nginx/image, and then check the local http://ip:9090/01.jpg to see if the picture can be accessed.

2. SpringBoot to upload resources

Pom.xml:

Org.springframework.boot spring-boot-starter-parent 2.1.7.RELEASE org.springframework.boot spring-boot-starter-web 2.1.7.RELEASE org.springframework.boot spring-boot-starter-test 2.1.7.RELEASE test org.apache.commons commons-lang3 3.8.1 org.apache.commons commons-io 1.3.2 commons-net commons-net 3.6 commons-fileupload commons-fileupload 1.3.3 org.projectlombok lombok 1.16 . 22 com.jcraft jsch 0.1.54 joda-time joda-time 2.10.3

Appilcation.yml:

Ftp: host: own server ip userName: server account password: server password port: 22 rootPath: / usr/nginx/image img: url: http://ip:9090/ # ftp.img.url may not be added. This is just to return the file path after the file is uploaded successfully.

Utility 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;@Componentpublic 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;} / * password * / private static String password @ Value ("${ftp.password}") public void setPassword (String val) {FtpUtil.password = val;} / * the root directory where the picture is stored * / private static String rootPath; @ Value ("${ftp.rootPath}") public void setRootPath (String val) {FtpUtil.rootPath = val;} / * the path to the image * / 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 root@host:port Session sshSession = jsch.getSession (userName,host,port); / / password 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 * @ param imagesName picture name * @ return urlStr image storage path * / 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 (); / / process the returned path 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 pictures * / 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 upload image name):

Import java.util.Random;public class IDUtils {/ * generate random picture name * / public static String genImageName () {/ / take the long shaping value of the current time including millisecond long millis = System.currentTimeMillis (); / / plus three-digit random number Random random = new Random (); int end3 = random.nextInt (999); / / if less than three digits before 0 String str = millis + String.format ("d", 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: 21:34 * / @ Service@Slf4jpublic 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 utility class to generate a new file name, new file name = newName + file suffix String newName = IDUtils.genImageName (); assert oldName! = null; newName = newName + oldName.substring (oldName.lastIndexOf (".")); / / 1.3 generate the subdirectory of the file stored on the server side String filePath = new DateTime (). ToString ("/ yyyyMMdd/") / / 2. Upload the picture to the image server / / 2.1get the uploaded io stream InputStream input = null; try {input = uploadFile.getInputStream ();} catch (IOException e) {e.printStackTrace ();} / 2.2 call the FtpUtil utility 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@Slf4jpublic class NginxController {@ Autowired private NginxService nginxService / * you can upload pictures and videos by configuring the recognized suffix * / @ 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) in the nginx configuration;} catch (JsonProcessingException e) {e.printStackTrace () } long end = System.currentTimeMillis (); log.info ("task ends, total time: [" + (end-begin) + "] milliseconds"); return json;} @ PostMapping ("/ uploads") public Object picturesUpload (@ RequestParam (value = "file") MultipartFile [] uploadFile) {long begin = System.currentTimeMillis (); Map 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 ends, total time: [" + (end-begin) + "] milliseconds"); return map;}} springboot is a new programming specification for springboot, which is designed to simplify the initial construction and development process of new Spring applications. SpringBoot is also a framework that serves the framework, and the scope of services is to simplify configuration files.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report