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();  
	    }  
	}
}
相关文章
相关标签/搜索