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 realize the function of uploading Resources with SpringBoot+nginx

2025-03-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "SpringBoot+nginx how to achieve resource upload function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "SpringBoot+nginx how to achieve resource upload function" bar!

1.nginx installation and configuration

The server used by the editor is Aliyun's lightweight application server, and the system uses ubuntu. Remember to open the 9090tcp port, or if you don't use port 9090 as the server port.

Installation

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

The editor puts the installation package in / usr/nginx, goes to the directory, and then executes tar-zxvf nginx-1.11.3.tar.gz to extract it.

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 see if the picture can be accessed locally.

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

Launch the project, a wave of postman artifacts

Note:

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

two。 The above code uploads API is used to upload multiple files.

Thank you for your reading, the above is the content of "how to achieve the resource upload function of SpringBoot+nginx". After the study of this article, I believe you have a deeper understanding of how to achieve the resource upload function of SpringBoot+nginx, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Development

Wechat

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

12
Report