上传图片

需要准备:
1.安装虚拟机,系统Linux CentOS6.4
2.Nginx
3.Vsftpd

1.安装虚拟机

VMware Workstation  ,系统Linux CentOS6.4用64位

2.安装nginx

1.使用yum形式安装,搜索CentOS6 yum nginx

rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm  
yum -y install nginx 

2.由于Nginx需要依赖其他地方库,在命令行输入:
yum install gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel –y
3.查看nginx安装版本

nginx -v

4.查看nginx安装的信息,如下图所示:
nginx -V

nginx配置文件.png

5.修改nginx的配置文件:
vim /etc/nginx/nginx.conf

nginx配置信息.png

打开子配置信息,配置ftpuser服务路径:

nginx配置信息1.png

6.启动、关闭、重启服务:
service nginx start
测试:打开火狐:localhost
service nginx stop
service nginx restart

3安装ftp服务(客户端安装FileZilla Client)

1.安装服务yum -y install vsftpd
2.添加一个ftp用户,此用户就是用来登录ftp服务器用的。
useradd ftpuser登录后默认的路径为 /home/ftpuser.
3.给ftp用户添加密码
passwd ftpuser输入两次密码后修改密码。
4.防火墙开启21端口,因为ftp默认的端口为21,而centos默认是没有开启的,所以要修改iptables文件
vim /etc/sysconfig/iptables
在行上面有22 -j ACCEPT 下面另起一行输入跟那行差不多的,只是把22换成21,然后:wq保存。
还要运行下,重启iptables。service iptables restart
5.修改selinux(外网是可以访问上去了,可是发现没法返回目录(使用ftp的主动模式,被动模式还是无法访问),也上传不了,因为selinux作怪了。)
修改selinux:
执行以下命令查看状态:
[root@bogon ~]# 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
[root@bogon ~]#
执行上面命令,再返回的结果看到两行都是off,代表,没有开启外网的访问
[root@bogon ~]# setsebool -P allow_ftpd_full_access on
[root@bogon ~]# setsebool -P ftp_home_dir on

这样应该没问题了(如果,还是不行,看看是不是用了ftp客户端工具用了passive模式访问了,如提示Entering Passive mode,就代表是passive模式,默认是不行的,因为ftp passive模式被iptables挡住了,下面会讲怎么开启,如果懒得开的话,就看看你客户端ftp是否有port模式的选项,或者把passive模式的选项去掉。如果客户端还是不行,看看客户端上的主机的电脑是否开了防火墙,关吧)

FileZilla的主动、被动模式修改:
菜单:编辑→设置
6.启动服务:service vsftpd restart

代码实现


package com.taotao.service;

import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

public interface PictureService {

    Map uploadPicture(MultipartFile uploadFile);
    
}

package com.taotao.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.PictureService;

/**
 * 图片上传服务
 * 
 * @author gyq
 *
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;

    @Override
    public Map uploadPicture(MultipartFile uploadFile) {
        Map<Object, Object> resultMap = new HashMap<>();
        try {
            // 生成一个新的文件名
            // 取原始文件名
            String oldName = uploadFile.getOriginalFilename();
            // 生成新的文件名
            // UUID.randomUUID();
            String newName = IDUtils.genImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            String imagePath = new DateTime().toString("/yyyy/MM/dd");
            // 图片上传
            boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH,
                    imagePath, newName, uploadFile.getInputStream());

            if (!result) {
                resultMap.put("error", 1);
                resultMap.put("message", "文件上传失败");
                return resultMap;
            }
            resultMap.put("error", 0);
            resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" + newName);
            return resultMap;
        } catch (Exception e) {
            resultMap.put("error", 1);
            resultMap.put("message", "文件上传异常");
            return resultMap;

        }

    }
}

junit测试

package com.taotao.controller;

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;

import com.taotao.common.utils.FtpUtil;

public class FTPTest {
    
    @Test
    public void testFtpClient() throws Exception{
        // 创建一个FtpClient对象
        FTPClient ftpClient =new FTPClient();
        //创建Ftp连接
        ftpClient.connect("192.168.84.128", 21);
        //登录ftp服务器,使用用户名和密码
        ftpClient.login("ftpuser", "123456");
        //上传图片
        //读取本地文件
        FileInputStream inputStream=new FileInputStream(new File("C:\\Users\\gyq\\Desktop\\hello1.jpg"));
        //设置上传的路径
        ftpClient.changeWorkingDirectory("/home/ftpuser/www/images");
        //修改上传文件的格式
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //第一个参数:服务器端文档名
        //第二个参数:上传文档的inputStream
        ftpClient.storeFile("hello1.jpg", inputStream);
        //关闭连接
        ftpClient.logout();
    }
    
    
    @Test
    public void testFtpUtil() throws Exception{
        
        FileInputStream inputStream=new FileInputStream(new File("C:\\Users\\gyq\\Desktop\\hello2.jpg"));
        FtpUtil.uploadFile("192.168.84.128", 21, "ftpuser", "123456", "/home/ftpuser/www/images", "/2017", "hello2.jpg", inputStream);
    }

}

表现层

package com.taotao.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.service.PictureService;

/**
 * 图片上传
 * 
 * @author gyq
 *
 */
@Controller
public class PictureController {
    @Autowired
    private PictureService pictureService;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public Map pictureUpLoad(MultipartFile uploadFile) {
        Map result = pictureService.uploadPicture(uploadFile);
        return result;

    }

}

resource.properties

#FTP配置文件
#FTP的ip地址
FTP_ADDRESS=192.168.84.128
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=123456
FTP_BASE_PATH=/home/ftpuser/www/images
#图片服务器相关配置
#图片服务器基础url
IMAGE_BASE_URL=http://192.168.84.128/images

applicationContext-dao.xml中修改加载配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 数据库连接池 -->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.taotao.mapper"></property>
    </bean>
</beans>

springmvc.xml中添加定义文件上传解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.taotao.controller" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 资源映射 -->
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
    
    <!-- 定义文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容