歡迎光臨
每天分享高質量文章

Nginx 搭建圖片伺服器

  • 本章知識點
  • 單元測試
  • Maven 的Web 專案
    • 專案核心配置檔案
    • Service 層
    • Controller 層
    • Views檢視層
  • 總結

本章內容透過Nginx 和 FTP 搭建圖片伺服器。在學習本章內容前,請確保您的Linux 系統已經安裝了Nginx和Vsftpd。

Nginx 安裝

http://www.cnblogs.com/itdragon/p/7850985.html

Vsftpd 安裝

http://www.cnblogs.com/itdragon/p/7857649.html


本章知識點

效果圖:

  • 需求:實現圖片的上傳和批次上傳
  • 技術:Nginx,Vsftpd,Spring,SpringMVC,KindEditor,CentOS
  • 說明:本章節內容主要是實現圖片的上傳功能。使用 KindEditer 是為了更好的演示圖片的上傳,回顯,批次效果。後臺程式碼與KindEditer沒有直接關係,放心閱讀。另外原始碼中有Mybatis的jar,不用理會,本章內容用不到,是為後續內容做準備!
  • 原始碼:見文章底部
  • 場景:使用者將圖片上傳到 tomcat 伺服器上,再由 tomcat 伺服器透過FTP上傳到 Nginx 伺服器上。

專案結構:


單元測試

首先要攻破核心技術。透過單元測試實現圖片上傳的功能。

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 {

    // 測試 ftp 上傳圖片功能
    @Test
    public void testFtpClient() throws Exception {
        // 1. 建立一個FtpClient物件
        FTPClient ftpClient = new FTPClient();
        // 2. 建立 ftp 連線
        ftpClient.connect("192.168.0.11"21);
        // 3. 登入 ftp 伺服器
        ftpClient.login("ftpuser""root");
        // 4. 讀取本地檔案
        FileInputStream inputStream = new FileInputStream(new File("F:\\hello.png"));
        // 5. 設定上傳的路徑
        ftpClient.changeWorkingDirectory("/usr/local/nginx/html/images");
        // 6. 修改上傳檔案的格式為二進位制
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        // 7. 伺服器儲存檔案,第一個引數是儲存在伺服器的檔案名,第二個引數是檔案流
        ftpClient.storeFile("hello.jpg", inputStream);
        // 8. 關閉連線
        ftpClient.logout();

    }

}

說明:這裡的ip地址,埠,ftp使用者名稱,密碼,本地檔案路徑,以及Nginx伺服器圖片路徑等,這些字串引數都要根據自己實際設定的來填寫的。如果你的Nginx和Vsftpd安裝是按照我提供的連結來做的。那你只需要改ip地址即可。


Maven 的Web 專案

搭建Maven的Web 專案,之前有寫過。這裡就不過多描述。

專案核心配置檔案

首先是 Maven 的核心檔案 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0modelVersion>


    <groupId>com.itdragon.uploadgroupId>
    <artifactId>pictrue-serviceartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

    
    <properties>
        <junit.version>4.12junit.version>
        <spring.version>4.1.3.RELEASEspring.version>
        <mybatis.version>3.2.8mybatis.version>
        <mybatis.spring.version>1.2.2mybatis.spring.version>
        <mybatis.paginator.version>1.2.15mybatis.paginator.version>
        <mysql.version>5.1.6mysql.version>
        <slf4j.version>1.6.4slf4j.version>
        <jackson.version>2.4.2jackson.version>
        <druid.version>1.0.9druid.version>
        <httpclient.version>4.3.5httpclient.version>
        <jstl.version>1.2jstl.version>
        <servlet-api.version>2.5servlet-api.version>
        <jsp-api.version>2.0jsp-api.version>
        <joda-time.version>2.5joda-time.version>
        <commons-lang3.version>3.3.2commons-lang3.version>
        <commons-io.version>1.3.2commons-io.version>
        <commons-net.version>3.3commons-net.version>
        <pagehelper.version>3.4.2pagehelper.version>
        <jsqlparser.version>0.9.1jsqlparser.version>
        <commons-fileupload.version>1.3.1commons-fileupload.version>
        <jedis.version>2.7.2jedis.version>
        <solrj.version>4.10.3solrj.version>
    properties>
    <dependencies>
        
        <dependency>
            <groupId>joda-timegroupId>
            <artifactId>joda-timeartifactId>
            <version>${joda-time.version}version>
        dependency>
        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>${commons-lang3.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-ioartifactId>
            <version>${commons-io.version}version>
        dependency>
        <dependency>
            <groupId>commons-netgroupId>
            <artifactId>commons-netartifactId>
            <version>${commons-net.version}version>
        dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>${jackson.version}version>
        dependency>
        
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>${httpclient.version}version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${slf4j.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>${mybatis.spring.version}version>
        dependency>
        <dependency>
            <groupId>com.github.miemiedevgroupId>
            <artifactId>mybatis-paginatorartifactId>
            <version>${mybatis.paginator.version}version>
        dependency>
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>${pagehelper.version}version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>${druid.version}version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>${spring.version}version>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>${jstl.version}version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>${servlet-api.version}version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jsp-apiartifactId>
            <version>${jsp-api.version}version>
            <scope>providedscope>
        dependency>
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>${commons-fileupload.version}version>
        dependency>
        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>${jedis.version}version>
        dependency>
        
        <dependency>
            <groupId>org.apache.solrgroupId>
            <artifactId>solr-solrjartifactId>
            <version>${solrj.version}version>
        dependency>
    dependencies>

    <build>
        <finalName>${project.artifactId}finalName>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-resources-pluginartifactId>
                <version>2.7version>
                <configuration>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.2version>
                <configuration>
                    <source>1.7source>
                    <target>1.7target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
        plugins>
        <pluginManagement>
            <plugins>
                
                <plugin>
                    <groupId>org.apache.tomcat.mavengroupId>
                    <artifactId>tomcat7-maven-pluginartifactId>
                    <version>2.2version>
                plugin>
            plugins>
        pluginManagement>
    build>
project>

說明:和檔案上傳有直接關係的是:

<dependency>
     <groupId>commons-fileuploadgroupId>


     <artifactId>commons-fileuploadartifactId>
dependency>

然後是 Web 專案的核心檔案 web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="taotao" version="2.5">

    <display-name>pictrue-servicedisplay-name>


    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring/applicationContext-*.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <servlet>
        <servlet-name>pictrue-serviceservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring/springmvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>pictrue-serviceservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

再是 SpringMVC 配置檔案 springmvc.xml,需要新增檔案上傳解析器


    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        
        <property name="defaultEncoding" value="UTF-8">property>


        
        <property name=“maxUploadSize” value=“5242880”>property>
    bean>

最後是 Ftp 配置檔案 resource.properties

FTP_ADDRESS=192.168.0.11
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=root
FTP_BASE_PATH=/usr/local/nginx/html/images
IMAGE_BASE_URL=http://192.168.0.11/images

Service 層

上傳圖片的介面 PictureService.java

package com.itdragon.service;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
public interface PictureService {

    /**
     * 上傳,批次上傳介面
     * @param uploadFile
     * @return
     */

    Map uploadPicture(MultipartFile uploadFile);
}

上傳圖片介面實現類 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 {

    // 透過 Spring4 的 Value註解,獲取配置檔案中的屬性值
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;     // ftp 伺服器ip地址
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;       // ftp 伺服器port,預設是21
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;    // ftp 伺服器使用者名稱
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;    // ftp 伺服器密碼
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;   // ftp 伺服器儲存圖片的絕對路徑
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;  // ftp 伺服器外網訪問圖片路徑

    @Override
    public Map uploadPicture(MultipartFile uploadFile) {
        Map resultMap = new HashMap<>();
        try {
            // 1. 取原始檔案名
            String oldName = uploadFile.getOriginalFilename();

            // 2. ftp 伺服器的檔案名
            String newName = oldName;
            //圖片上傳
            boolean result = uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, 
                    uploadFile.getInputStream(), FTP_BASE_PATH, newName);
            //傳回結果
            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 上傳圖片方法
     * @param ip            ftp 伺服器ip地址
     * @param port          ftp 伺服器port,預設是21
     * @param account       ftp 伺服器使用者名稱
     * @param passwd        ftp 伺服器密碼
     * @param inputStream   檔案流
     * @param workingDir    ftp 伺服器儲存圖片的絕對路徑
     * @param fileName      上傳到ftp 伺服器檔案名
     * @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. 建立一個FtpClient物件
        FTPClient ftpClient = new FTPClient();
        try {
            // 2. 建立 ftp 連線
            ftpClient.connect(ip, port);
            // 3. 登入 ftp 伺服器
            ftpClient.login(account, passwd);
            int reply = ftpClient.getReplyCode(); // 獲取連線ftp 狀態傳回值
            System.out.println("code : " + reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect(); // 如果傳回狀態不再 200 ~ 300 則認為連線失敗
                return result;
            }
            // 4. 讀取本地檔案
//          FileInputStream inputStream = new FileInputStream(new File("F:\\hello.png"));
            // 5. 設定上傳的路徑
            ftpClient.changeWorkingDirectory(workingDir);
            // 6. 修改上傳檔案的格式為二進位制
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 7. 伺服器儲存檔案,第一個引數是儲存在伺服器的檔案名,第二個引數是檔案流
            if (!ftpClient.storeFile(fileName, inputStream)) {
                return result;
            }
            // 8. 關閉連線
            inputStream.close();
            ftpClient.logout();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // FIXME 聽說,專案裡面最好少用try catch 捕獲異常,這樣會導致Spring的事務回滾出問題???難道之前寫的程式碼都是假程式碼!!!
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

}

說明:

  • @Value 註解是Spring4 中提供的,@Value(“${XXX}”)
  • 傳回值是一個Map,並且key有error,url,message。這是根據KindEditer的語法要求來的。詳情見連結。http://kindeditor.net/docs/upload.html

Controller 層

負責頁面跳轉的 PageController.java

package com.itdragon.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {

    /**
     * 開啟首頁
     */

    @RequestMapping("/")
    public String showIndex() {
        return "index";
    }

    @RequestMapping("/{page}")
    public String showpage(@PathVariable String page) {
        System.out.println("page : " + page);
        return page;
    }
}

負責圖片上傳的 PictureController.java

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;

@RestController
public 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);
            // 瀏覽器擅長處理json格式的字串,為了減少因為瀏覽器核心不同導致的bug,建議用json
            json = new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }
}

說明:

  • @RestController 也是Spring4 提供的,是 @Controller + @ResponseBody 的組合註解。
  • Controller層的傳回值是一個json格式的字串。是考慮到瀏覽器對json解析相容性比較好。

Views檢視層

負責上傳圖片的jsp頁面 pic-upload.jsp

<%@ page language="java" contentType="text/html; UTF-8" pageEncoding="UTF-8"%>
html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ITDragon 圖片上傳title>


head>
    <link href=“/js/kindeditor-4.1.10/themes/default/default.css” type=“text/css” rel=“stylesheet”>
    <script type=“text/javascript” src=“js/jquery.min.js”>script
    <script type=“text/javascript” charset=“utf-8” src=“/js/kindeditor-4.1.10/kindeditor-all-min.js”>script>
    <script type=“text/javascript” charset=“utf-8” src=“/js/kindeditor-4.1.10/lang/zh_CN.js”>script>
head>  
<body>  
    <h3>測試上傳圖片功能介面的form表單h3>
    <form action=“pic/upload” method=“post” enctype=“multipart/form-data”>
        <input type=“file” name=“fileUpload” />
        <input type=“submit” value=“上傳檔案” />
    form>
    <hr />
    <h3>借用KindEditor富文字編輯器實現批次上傳圖片h3>
    <textarea id=“kindEditorDesc” style=“width:800px;height:300px;visibility:hidden;”>textarea>
    <script type=“text/javascript”>
        $(function(){
            //初始化富文字編輯器
            KindEditor.create(“#kindEditorDesc”, {
                // name值,必須和Controller 的引數對應,不然會提示 400 的錯誤
                filePostName : “fileUpload”,
                // action值,
                uploadJson : ‘/pic/upload’,
                // 設定上傳型別,分別為image、flash、media、file
                dir : “image”
            });
        });
    
script>   
body>
html>

說明:pic-upload.jsp 分為兩個部分,第一個部分是為了測試上傳圖片功能的form表單。第二個部分是為了更好的體驗上傳,批次上傳,回顯功能的KindEditer 富文字編輯器。


總結

  • Nginx 搭建伺服器的思維
  • Java實現 Ftp上傳圖片的功能
  • KindEditer 上傳圖片的功能

原始碼:https://github.com/ITDragonBlog/daydayup/tree/master/Nginx

Nginx 搭建圖片伺服器到這裡就結束了,有什麼不足的地方,請賜教。如果覺得不錯,可以點個贊哦!

贊(0)

分享創造快樂