上傳圖片

需要準備:
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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容