nginx+ftp搭建圖片服務器

1、須要的組件

圖片服務器兩個服務:php

Nginx(圖片訪問):

一、http服務:可使用nginx作靜態資源服務器。也可使用apache。推薦使用nginx,效率更高。html

二、反向代理 實現 負載均衡java

ftp服務(圖片上傳):

使用linux作服務器,在linux中有個ftp組件vsftpd。linux

2、Nginx服務器搭建

1.安裝Nginx

要求安裝vmware虛擬機。nginx

Linux:CentOS6.4(32)apache

Nginx:1.8.0vim

Vsftpd:須要在線安裝。centos

虛擬機以及Linux安裝很簡單此處略。bash

Linux的局域網IP爲:192.168.1.110服務器

修改Linux的IP並當即生效的命令:

#切換root管理員用戶
[root@localhost ~]# su
password 
#設置本機IP並當即生效   
[root@localhost ~]# ifconfig eth0 192.168.1.110 netmask 255.255.255.0

1.一、nginx安裝環境(詳見nginx安裝手冊)

nginx安裝手冊:https://pan.baidu.com/s/1VHxSfMBU_H5pCS6eHD3r5Q

1.二、把nginx安裝包nginx-1.8.0.tar.gz上傳到服務器。

在secureCRT打開sftp會話框,上傳文件

使用put/get命令 或者直接拖拽文件

1.三、解壓縮(在安裝包所在目錄執行)

[root@localhost ~]# tar -zxvf nginx-1.8.0.tar.gz

1.四、配置makefile

進入解壓後的目錄

[root@localhost ~]# cd nginx-1.8.0

執行下面的命令建立makefile

./configure \

--prefix=/usr/local/nginx \

--pid-path=/var/run/nginx/nginx.pid \

--lock-path=/var/lock/nginx.lock \

--error-log-path=/var/log/nginx/error.log \

--http-log-path=/var/log/nginx/access.log \

--with-http_gzip_static_module \

--http-client-body-temp-path=/var/temp/nginx/client \

--http-proxy-temp-path=/var/temp/nginx/proxy \

--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \

--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \

--http-scgi-temp-path=/var/temp/nginx/scgi

注意:上邊將臨時文件目錄指定爲/var/temp/nginx,須要在/var下建立temp及nginx目錄

[root@bogon nginx-1.8.0]# mkdir /var/temp/nginx -p

1.五、編譯安裝

編譯:

[root@localhost nginx-1.8.0]# make

安裝:

[root@localhost nginx-1.8.0]# make  install

安裝成功之後進入安裝目錄(建立makedir時指定的」--prefix=/usr/local/nginx \「)

[root@localhost nginx-1.8.0]# cd /usr/local/nginx/

 

二、nginx運行

2.一、啓動nginx

[root@localhost nginx]# cd sbin
[root@localhost sbin]# ./nginx

2.二、關閉

[root@localhost sbin]# ./nginx -s stop

2.三、從新加載配置文件

[root@localhost sbin]# ./nginx -s reload

2.四、關閉防火牆

1)關閉

[root@localhost sbin]# service iptables stop

iptables: Flushing firewall rules:                         [  OK  ]

iptables: Setting chains to policy ACCEPT: filter          [  OK  ]

iptables: Unloading modules:                               [  OK  ]

2)也能夠修改防火牆配置文件:

[root@localhost sbin]# vim /etc/sysconfig/iptables
//在倒數第二行加入80端口  
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

修改後須要重啓防火牆:

[root@localhost sbin]# service iptables restart

3)另一種解決辦法

[root@localhost ]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT  
[root@localhost ]# /etc/init.d/iptables save  
[root@localhost ]# /etc/init.d/iptables restart

2.五、訪問nginx服務

 

三、關於圖片服務器配置

進入配置文件目錄

cd /usr/local/nginx/conf/

nginx的默認配置文件nginx.config

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

配置圖片服務器

方法1、在配置文件server{}中location /{} 修改配置:

#默認請求
location / {
   root  /home/ftpuser/www;#定義服務器的默認網站根目錄位置
   index index.html index.php index.htm;#定義首頁索引文件的名稱
}

其中:/home/ftpuser/www;爲建立FTP服務帳戶ftpuser的根目錄下的www目錄

方法2、在http{}內配置新服務

server {
        listen       8080;
        server_name  localhost;

        #charset utf-8;

        #access_log  logs/host.access.log  main;

        #默認請求
        location / {
            root  /home/ftpuser/www;#定義服務器的默認網站根目錄位置
            index index.html index.php index.htm;#定義首頁索引文件的名稱
           }
        }

最後在配置文件最上面第一行添加 user ftpuser; 表示nginx使用該帳戶訪問文件

由於須要開始端口號8080,因此要在防火牆中開啓8080端口

[root@localhost ]# /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT  
[root@localhost ]# /etc/init.d/iptables save  
[root@localhost ]# /etc/init.d/iptables restart

3、FTP服務的安裝與啓動

一、安裝vsftpd組件

vsftpd組件爲Linux的FTP服務組件,安裝方式爲在線安裝。

[root@localhost ~]# yum -y install vsftpd

安裝完後,有/etc/vsftpd/vsftpd.conf 文件,是vsftp的配置文件。

二、添加一個ftp用戶

此用戶就是用來登陸ftp服務器用的。

[root@localhost ~]# useradd ftpuser

這樣一個用戶建完,能夠用這個登陸,記得用普通登陸不要用匿名了。登陸後默認的路徑爲 /home/ftpuser.

爲這個ftp帳戶添加密碼

[root@localhost ~]# passwd ftpuser

輸入兩次密碼後修改密碼。

三、 防火牆開啓21端口

由於ftp默認的端口爲21,而centos默認是沒有開啓的,因此要修改iptables文件

[root@localhost ~]# vim /etc/sysconfig/iptables

在行上面有22 -j ACCEPT 下面另起一行輸入跟那行差很少的,只是把22換成21,而後:wq保存。

還要運行下,重啓iptables

[root@localhost ~]# service iptables restart

四、 修改selinux

外網是能夠訪問上去了,但是發現無法返回目錄(使用ftp的主動模式,被動模式仍是沒法訪問),也上傳不了,由於selinux做怪了。

修改selinux:

執行如下命令查看狀態:

[root@localhost ~]# getsebool -a | grep ftp  

allow_ftpd_anon_write --> off

allow_ftpd_full_access --> off

allow_ftpd_use_cifs --> off

allow_ftpd_use_nfs --> off

ftp_home_dir --> off

ftpd_connect_db --> off

ftpd_use_passive_mode --> off

httpd_enable_ftp_server --> off

tftp_anon_write --> off

執行上面命令,再返回的結果看到兩行都是off,表明,沒有開啓外網的訪問

[root@localhost ~]# setsebool -P allow_ftpd_full_access on

[root@localhost ~]# setsebool -P ftp_home_dir on

這樣應該沒問題了(若是,仍是不行,看看是否是用了ftp客戶端工具用了passive模式訪問了,如提示Entering Passive mode,就表明是passive模式,默認是不行的,由於ftp passive模式被iptables擋住了,下面會講怎麼開啓,若是懶得開的話,就看看你客戶端ftp是否有port模式的選項,或者把passive模式的選項去掉。若是客戶端仍是不行,看看客戶端上的主機的電腦是否開了防火牆,關吧)

FileZilla的主動、被動模式修改:

菜單:編輯→設置

五、關閉匿名訪問

修改/etc/vsftpd/vsftpd.conf文件:

 

重啓ftp服務:

[root@localhost ~]# service vsftpd restart

六、 開啓被動模式

默認是開啓的,可是要指定一個端口範圍,打開vsftpd.conf文件,在後面加上

pasv_min_port=30000
pasv_max_port=30999

表示端口範圍爲30000~30999,這個能夠隨意改。改完重啓一下vsftpd

因爲指定這段端口範圍,iptables也要相應的開啓這個範圍,因此像上面那樣打開iptables文件。

也是在21上下面另起一行,更那行差很少,只是把21 改成30000:30999,而後:wq保存,重啓下iptables。這樣就搞定了。

七、設置開機啓動vsftpd ftp服務

[root@localhost ~]# chkconfig vsftpd on

4、部署驗證

在www下新建文件夾images,下面放一張圖片001.jpg

測試訪問:http://192.168.1.110/images/001.jpg

5、Java實現FTP上傳

上傳文件測試代碼:

package com.taotao.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;

import com.taotao.util.FtpUtil;

public class FTPTest {
	@Test
	public void testFtpClient() throws SocketException, IOException {
		FTPClient ftpClient = new FTPClient();
		try {
			// 鏈接FTP服務器
			ftpClient.connect("192.168.1.110", 21);
			// 登陸FTP服務器
			ftpClient.login("ftpuser", "123");
			// 將文件轉換爲IO
			FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\a\\Pictures\\16-040836_50.jpg"));
			// 指定上傳遠程目錄
			ftpClient.changeWorkingDirectory("/home/ftpuser/www/images");// 絕對路徑
			// ftpClient.changeWorkingDirectory("www/images");//相對路徑
			// 設置上傳文件類型
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			// 上傳文件並指定遠程文件名
			// ftpClient.storeFile("中文名.jpg", fileInputStream);//中文會出現亂碼
			ftpClient.storeFile("a.jpg", fileInputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 退出登陸
			ftpClient.logout();
			// 斷開鏈接
			ftpClient.disconnect();
		}

	}

	@Test
	public void testFTPUtil() {
		try {
			FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\a\\Pictures\\16-040836_50.jpg"));
			String filename=new String("中文名2.jpg".getBytes("utf-8"),"iso-8859-1");//解決中文文件名亂碼
			FtpUtil.uploadFile("192.168.1.110", 21, "ftpuser", "123", "/home/ftpuser/www/images", "/2016/09/26",filename ,
					fileInputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

其中FtpUtil類:

package com.taotao.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * ftp上傳下載工具類
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 
 * @author	入雲龍
 * @date	2015年7月29日下午8:11:51
 * @version 1.0
 */
public class FtpUtil {

	/** 
	 * Description: 向FTP服務器上傳文件 
	 * @param host FTP服務器hostname 
	 * @param port FTP服務器端口 
	 * @param username FTP登陸帳號 
	 * @param password FTP登陸密碼 
	 * @param basePath FTP服務器基礎目錄,須要絕對路徑 好比:/home/ftpuser/www/images
	 * @param filePath FTP服務器文件存放路徑。例如分日期存放:/2015/01/01。文件的路徑爲basePath+filePath
	 * @param filename 上傳到FTP服務器上的文件名 
	 * @param input 輸入流 
	 * @return 成功返回true,不然返回false 
	 */  
	public static boolean uploadFile(String host, int port, String username, String password, String basePath,
			String filePath, String filename, InputStream input) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);// 鏈接FTP服務器
			// 若是採用默認端口,可使用ftp.connect(host)的方式直接鏈接FTP服務器
			ftp.login(username, password);// 登陸
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			//切換到上傳目錄
			if (!ftp.changeWorkingDirectory(basePath+filePath)) {
				//若是目錄不存在建立目錄
				String[] dirs = filePath.split("/");
				String tempPath = basePath;
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) continue;
					tempPath += "/" + dir;
					if (!ftp.changeWorkingDirectory(tempPath)) {
						if (!ftp.makeDirectory(tempPath)) {
							return result;
						} else {
							ftp.changeWorkingDirectory(tempPath);
						}
					}
				}
			}
			//設置上傳文件的類型爲二進制類型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			//上傳文件
			if (!ftp.storeFile(filename, input)) {
				return result;
			}
			input.close();
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	/** 
	 * Description: 從FTP服務器下載文件 
	 * @param host FTP服務器hostname 
	 * @param port FTP服務器端口 
	 * @param username FTP登陸帳號 
	 * @param password FTP登陸密碼 
	 * @param remotePath FTP服務器上的相對路徑 
	 * @param fileName 要下載的文件名 
	 * @param localPath 下載後保存到本地的路徑 
	 * @return 
	 */  
	public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
			String fileName, String localPath) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);
			// 若是採用默認端口,可使用ftp.connect(host)的方式直接鏈接FTP服務器
			ftp.login(username, password);// 登陸
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);// 轉移到FTP服務器目錄
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());

					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}

			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		try {  
	        FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));  
	        boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);  
	        System.out.println(flag);  
	    } catch (FileNotFoundException e) {  
	        e.printStackTrace();  
	    }  
	}
}
相關文章
相關標籤/搜索