In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about how Nginx builds a picture server. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Effect picture:
Requirements: achieve picture upload and batch upload
Technology: Nginx,Vsftpd,Spring,SpringMVC,KindEditor,CentOS
Description: the main content of this chapter is to achieve the function of uploading pictures. KindEditer is used to better demonstrate the upload, echo and batch effect of pictures. The background code is not directly related to KindEditer, so feel free to read it. In addition, there is Mybatis's jar in the source code, never mind, the content of this chapter is not needed, it is to prepare for the follow-up content!
Source code: see the bottom of the article
Scenario: the user uploads the image to the tomcat server, and then the tomcat server uploads the image to the Nginx server through FTP.
Project structure:
Unit testing
The first step is to break through the core technology. Through the unit test to achieve the function of picture upload.
Package com.itdragon.test;import java.io.File;import java.io.FileInputStream;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.junit.Test;public class PictureFTPTest {/ / Test ftp upload function @ Test public void testFtpClient () throws Exception {/ / 1. Create a FtpClient object FTPClient ftpClient = new FTPClient (); / / 2. Create a ftp connection ftpClient.connect ("192.168.0.11", 21); / / 3. Log in to the ftp server ftpClient.login ("ftpuser", "root"); / / 4. Read the local file FileInputStream inputStream = new FileInputStream (new File ("F:\\ hello.png"); / / 5. Set the upload path ftpClient.changeWorkingDirectory ("/ usr/local/nginx/html/images"); / / 6. Modify the format of the uploaded file to binary ftpClient.setFileType (FTP.BINARY_FILE_TYPE); / / 7. The server stores files, the first parameter is the file name stored in the server, and the second parameter is the file stream ftpClient.storeFile ("hello.jpg", inputStream); / / 8. Close the connection ftpClient.logout ();}}
Description: here the ip address, port, ftp user name, password, local file path, and Nginx server image path, these string parameters should be filled in according to their own actual settings. If your Nginx and Vsftpd installation is done by following the links I provide. Then you just need to change the ip address.
Maven's Web project
Build the Web project for Maven, which has been written before. It won't be described too much here.
Project core profile
The first is the core file pom.xml of Maven.
4.0.0 com.itdragon.upload pictrue-service 0.0.1-SNAPSHOT war 4.12 4.1.3.RELEASE 3.2.8 1.2.2 1.2.15 5.1.6 1.6.4 2.4.2 1.0.9 4.3.5 1.2 2.5 2.0 2.5 3.3.2 1.3.2 3.3 3.4. 2 0.9.1 1.3.1 2.7.2 4.10.3 joda-time joda-time ${joda-time.version} org.apache.commons commons-lang3 ${commons-lang3.version} org.apache.commons commons-io ${commons-io.version} commons-net commons -net ${commons-net.version} com.fasterxml.jackson.core jackson-databind ${jackson.version} org.apache.httpcomponents httpclient ${httpclient.version} junit junit ${junit.version} test org.slf4j slf4j-log4j12 ${slf4j.version} Org.mybatis mybatis ${mybatis.version} org.mybatis mybatis-spring ${mybatis.spring.version} com.github.miemiedev mybatis-paginator ${mybatis.paginator.version} com.github.pagehelper pagehelper ${pagehelper.version} mysql mysql-connector-java ${mysql.version} Com.alibaba druid ${druid.version} org.springframework spring-context ${spring.version} org.springframework spring-beans ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-jdbc ${spring.version} Org.springframework spring-aspects ${spring.version} jstl jstl ${jstl.version} javax.servlet servlet-api ${servlet-api.version} provided javax.servlet jsp-api ${jsp-api.version} provided commons-fileupload commons-fileupload ${commons-fileupload. Version} redis.clients jedis ${jedis.version} org.apache.solr solr-solrj ${solrj.version} ${project.artifactId} org.apache.maven.plugins maven-resources-plugin 2.7 UTF-8 Org.apache.maven.plugins maven-compiler-plugin 3.2 1.7 1.7 UTF-8 org.apache.tomcat.maven tomcat7-maven-plugin 2.2
Description: what is directly related to file uploading is:
Commons-fileupload commons-fileupload
Then there is the core file web.xml of the Web project.
Pictrue-service contextConfigLocation classpath:spring/applicationContext-*.xml org.springframework.web.context.ContextLoaderListener CharacterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding utf-8 CharacterEncodingFilter / * pictrue-service org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring/springmvc.xml 1 pictrue-service /
Then there is the SpringMVC configuration file springmvc.xml, which needs to add a file upload parser.
Finally, the Ftp configuration file resource.properties
FTP_ADDRESS=192.168.0.11FTP_PORT=21FTP_USERNAME=ftpuserFTP_PASSWORD=rootFTP_BASE_PATH=/usr/local/nginx/html/imagesIMAGE_BASE_URL= http://192.168.0.11/images
Service layer
The API PictureService.java for uploading pictures
Package com.itdragon.service;import java.util.Map;import org.springframework.web.multipart.MultipartFile;public interface PictureService {/ * upload, batch upload API * @ param uploadFile * @ return * / Map uploadPicture (MultipartFile uploadFile);}
Upload picture API implementation class PictureServiceImpl.java
Package com.itdragon.service.impl;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPReply;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import com.itdragon.service.PictureService @ Service@SuppressWarnings ({"rawtypes", "unchecked"}) public class PictureServiceImpl implements PictureService {/ / obtain the attribute value @ Value ("${FTP_ADDRESS}") private String FTP_ADDRESS; / / ftp server ip address @ Value ("${FTP_PORT}") private Integer FTP_PORT; / / ftp server port in the configuration file through the Value annotation of Spring4. The default is 21 @ Value ("${FTP_USERNAME}") private String FTP_USERNAME. / / ftp server user name @ Value ("${FTP_PASSWORD}") private String FTP_PASSWORD; / / ftp server password @ Value ("${FTP_BASE_PATH}") private String FTP_BASE_PATH; / / absolute path of the ftp server to store pictures @ Value ("${IMAGE_BASE_URL}") private String IMAGE_BASE_URL / / ftp server public network access image path @ Override public Map uploadPicture (MultipartFile uploadFile) {Map resultMap = new HashMap (); try {/ / 1. Take the original file name String oldName = uploadFile.getOriginalFilename (); / / 2.The file name of the ftp server String newName = oldName; / / Image upload boolean result = uploadFile (FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, uploadFile.getInputStream (), FTP_BASE_PATH, newName); / / return the result if (! result) {resultMap.put ("error", 1) ResultMap.put ("message", "upload Fail"); return resultMap;} resultMap.put ("error", 0); resultMap.put ("url", IMAGE_BASE_URL + "/" + newName); return resultMap;} catch (Exception e) {e.printStackTrace (); resultMap.put ("error", 1); resultMap.put ("message", "upload Fail") Return resultMap }} / * ftp upload picture method * @ param ip ftp server ip address * @ param port ftp server port The default is 21 * @ param account ftp server user name * @ param passwd ftp server password * @ param inputStream file stream * @ absolute path where the param workingDir ftp server stores images * @ param fileName uploaded to the ftp server file name * @ throws Exception * * / public boolean uploadFile (String ip, Integer port, String account, String passwd, InputStream inputStream, String workingDir String fileName) throws Exception {boolean result = false / / 1. Create a FtpClient object FTPClient ftpClient = new FTPClient (); try {/ / 2. Create ftp connection ftpClient.connect (ip, port); / / 3. Log in to the ftp server ftpClient.login (account, passwd); int reply = ftpClient.getReplyCode (); / / get the connection ftp status return value System.out.println ("code:" + reply); if (! FTPReply.isPositiveCompletion (reply)) {ftpClient.disconnect (); / / if the returned status is no longer 200300, the connection is considered to have failed return result;} / / 4. Read the local file / / FileInputStream inputStream = new FileInputStream (new File ("F:\\ hello.png")); / / 5. Set the upload path ftpClient.changeWorkingDirectory (workingDir); / / 6. Modify the format of the uploaded file to binary ftpClient.setFileType (FTP.BINARY_FILE_TYPE); / / 7. The server stores files, the first parameter is the file name stored in the server, and the second parameter is the file stream if (! ftpClient.storeFile (fileName, inputStream)) {return result;} / / 8. Close the connection inputStream.close (); ftpClient.logout (); result = true;} catch (Exception e) {e.printStackTrace ();} finally {/ / FIXME heard that it is best to use less try catch to catch exceptions in the project, which will lead to problems with Spring transaction rollback. Is it possible that all the code written before is fake code! If (ftpClient.isConnected ()) {try {ftpClient.disconnect ();} catch (IOException ioe) {}} return result;}}
Description:
The ① @ Value annotation is provided in Spring4, @ Value ("${XXX}")
The return value of ② is a Map, and key has error,url,message. This is based on the grammatical requirements of KindEditer.
Controller layer
PageController.java in charge of page jump
Package com.itdragon.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class PageController {/ * Open the home page * / @ RequestMapping ("/") public String showIndex () {return "index";} @ RequestMapping ("/ {page}") public String showpage (@ PathVariable String page) {System.out.println ("page:" + page) Return page;}}
PictureController.java responsible for uploading pictures
Package com.itdragon.controller;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.itdragon.service.PictureService;@RestControllerpublic class PictureController {@ Autowired private PictureService pictureService @ RequestMapping ("pic/upload") public String pictureUpload (@ RequestParam (value = "fileUpload") MultipartFile uploadFile) {String json = "; try {Map result = pictureService.uploadPicture (uploadFile); / / browsers are good at handling strings in json format. In order to reduce bug caused by different browser kernels, it is recommended to use json json = new ObjectMapper (). WriteValueAsString (result);} catch (JsonProcessingException e) {e.printStackTrace () } return json;}}
Description:
① @ RestController is also provided by Spring4 and is a combined annotation of @ Controller + @ ResponseBody.
The return value of the ② Controller layer is a string in json format. It is considered that the browser has good compatibility with json parsing.
Views View layer
Pic-upload.jsp, the jsp page responsible for uploading pictures
The form form of the ITDragon picture upload test upload function interface uses the KindEditor rich text editor to achieve batch upload of pictures $(function () {/ / initialize the rich text editor KindEditor.create ("# kindEditorDesc", {/ / name value), which must correspond to the parameters of Controller. Otherwise, it will prompt the error filePostName: "fileUpload", / / action value, uploadJson:'/ pic/upload', / / set upload type: image, flash, media, file dir: "image"}) })
Description: pic-upload.jsp is divided into two parts, the first part is to test the form form for uploading pictures. The second part is to better experience upload, batch upload, echo function of the KindEditer rich text editor.
Thank you for reading! This is the end of the article on "how to build a picture server in Nginx". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.