SpringMVC整合FastDFS之文件上传详解

一、引入POM依赖



<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.wanggroupId>
    <artifactId>SpringDemoartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        
        <spring.version>4.3.8.RELEASEspring.version>
        <commons-fileupload.version>1.3.1commons-fileupload.version>
    properties>

    <dependencies>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <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-txartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>6.0.6version>
        dependency>

        
        <dependency>
            <groupId>org.csource.fastdfsgroupId>
            <artifactId>fastdfsartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>${commons-fileupload.version}version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.2version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.36version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.12version>
            <scope>providedscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                    <showWarnings>trueshowWarnings>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
                <configuration>
                    <port>8080port>
                    <path>/path>
                    <uriEncoding>UTF-8uriEncoding>
                    <server>tomcat7server>
                configuration>
            plugin>
        plugins>
    build>
project>

二、配置Web.xml


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

    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:application-mvc.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <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>

    <welcome-file-list>
        <welcome-file>/WEB-INF/jsp/index.jspwelcome-file>
    welcome-file-list>
web-app>

三、applicationContext-SpringMVC.xml配置


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    
    <context:property-placeholder location="classpath*:*.properties"/>
    
    <context:annotation-config/>
    
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="application/json"/>
                <property name="features">
                    <array>
                        <value>WriteMapNullValuevalue>
                        <value>WriteDateUseDateFormatvalue>
                    array>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
    
    <mvc:default-servlet-handler/>
    
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>

    
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8">property>
        
        <property name="maxUploadSize" value="5242880">property>
    bean>

    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
    
    <context:component-scan base-package="com.wang.controller"/>

beans>

四 、application.properties配置(配置文件服务器ip)

FILE_SERVER_URL=192.168.100.21/

五、fdfs_client.conf文件配置(FastDFS核心配置)

# connect timeout in seconds
# default value is 30s
connect_timeout=30

# network timeout in seconds
# default value is 30s
network_timeout=60

# the base path to store log files
base_path=/home/fastdfs

# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
#  配置自己的服务器地址和端口
tracker_server=192.168.100.21:22122

#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info

# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false

# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600

# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false

# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false

# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf


#HTTP settings
http.tracker_server_port=80

#use "#include" directive to include HTTP other settiongs
##include http.conf


六、日志的配置文件

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

七、创建文件上传的工具类

package com.wang.common;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.BufferedOutputStream;
import java.io.IOException;

/**
 * @author Administrator
 */
public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;

    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        ClientGlobal.init(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法
     * 

Title: uploadFile

*

Description:

* * @param fileName 文件全路径 * @param extName 文件扩展名,不包含(.) * @param metas 文件扩展信息 * @return * @throws Exception */
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { return storageClient.upload_file1(fileName, extName, metas); } /** * 上传文件,传fileName * * @param fileName 文件的磁盘路径名称 如:D:/image/aaa.jpg * @return null为失败 */ public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } /** * @param fileName 文件的磁盘路径名称 如:D:/image/aaa.jpg * @param extName 文件的扩展名 如 txt jpg等 * @return null为失败 */ public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上传文件方法 *

Title: uploadFile

*

Description:

* * @param fileContent 文件的内容,字节数组 * @param extName 文件扩展名 * @param metas 文件扩展信息 * @return * @throws Exception */
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { return storageClient.upload_file1(fileContent, extName, metas); } /** * 上传文件 * * @param fileContent 文件的字节数组 * @return null为失败 * @throws Exception */ public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } /** * 上传文件 * * @param fileContent 文件的字节数组 * @param extName 文件的扩展名 如 txt jpg png 等 * @return null为失败 */ public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } /** * 文件下载到磁盘 * * @param path 图片路径 * @param output 输出流 中包含要输出到磁盘的路径 * @return -1失败,0成功 */ public int download_file(String path, BufferedOutputStream output) { int result = -1; try { byte[] b = storageClient.download_file1(path); try { if (b != null) { output.write(b); result = 0; } } catch (Exception e) { } //用户可能取消了下载 finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } return result; } /** * 获取文件数组 * * @param path 文件的路径 如group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg * @return */ public byte[] download_bytes(String path) { byte[] b = null; try { b = storageClient.download_file1(path); } catch (Exception e) { e.printStackTrace(); } return b; } /** * 删除文件 * * @param group 组名 如:group1 * @param storagePath 不带组名的路径名称 如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg * @return -1失败,0成功 */ public Integer delete_file(String group, String storagePath) { int result = -1; try { result = storageClient.delete_file(group, storagePath); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * @param storagePath 文件的全部路径 如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg * @return -1失败,0成功 * @throws IOException * @throws Exception */ public Integer delete_file(String storagePath) { int result = -1; try { result = storageClient.delete_file1(storagePath); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 获取远程服务器文件资源信息 * * @param groupName 文件组名 如:group1 * @param remoteFileName M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg * @return */ public FileInfo getFile(String groupName, String remoteFileName) { try { return storageClient.get_file_info(groupName, remoteFileName); } catch (Exception e) { e.printStackTrace(); } return null; } }

八、创建文件上传得Controller

package com.wang.controller;

import com.wang.common.FastDFSClient;
import com.wang.user.User;
import org.springframework.beans.factory.annotation.Value;
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;


/**
 * @author:xian
 * @data:2020/3/19 0019 周四
 */
@Controller
public class SpringController {


    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @RequestMapping("/hello")
    public String springDemo() {

        return "hello";
    }


    /**
     * 文件上传
     *
     * @param file 上传文件对象
     * @return 文件上传路径
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {

        String URL = "上传失败";
        //获取文件路径
        String path = file.getOriginalFilename();
        //获取文件后缀名
        String extName = path.substring(path.lastIndexOf(".") + 1);
        try {
            //读取配置文件
            FastDFSClient client = new FastDFSClient("classpath:fdfs_client.conf");
            String filePath = client.uploadFile(file.getBytes(), extName);
            URL = FILE_SERVER_URL + filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return URL;
    }


    @RequestMapping("/user")
    @ResponseBody
    public User getUser() {

        return new User().setUserName("xian").setPassWord("xian");
    }

    /**
     * 表单数据SpringMVC会自动解析封装成对象
     *
     * @param user
     * @return
     */
    @RequestMapping("/postUser")
    @ResponseBody
    public User postUser(User user) {
        return user;
    }

}


九、创建上传得JSP页面(此处简单测试)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>单图片上传</title>
</head>
<body>
<fieldset>
    <legend>图片上传</legend>
    <h2>只能上传单张10M以下的 PNG、JPG、GIF 格式的图片</h2>
    <form action="/upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file">
                <input type="submit" value="上传">
    </form>
</fieldset>
</body>
</html>

十、通过浏览器访问FastDFS返回的地址即可看到我们上传到服务器上的文件,当然这个文件不局限于图片。

你可能感兴趣的:(SpringMVC框架,FastDFS)