1. 程式人生 > >FastDFS上傳簡單Demo

FastDFS上傳簡單Demo

  FastDFS是一個輕量級的分散式檔案系統,它對檔案的管理功能包括:檔案儲存、檔案同步、檔案訪問等,解決了大容量儲存和負載均衡的問題。下面是Demo的程式碼,採用的是Spring MVC框架。

開發工具:Eclipse

jar包管理:Maven

JDK:1.8

1、首先建立Maven專案

  File-->New-->Project-->Maven Project

2、新增依賴的jar包

  修改pom.xml檔案,新增以下依賴:

<properties>
	<spring.version>4.1.3.RELEASE</spring.version>
	<httpclient.version>4.3.5</httpclient.version>
	<jstl.version>1.2</jstl.version>
	<servlet-api.version>2.5</servlet-api.version>
	<jsp-api.version>2.0</jsp-api.version>
	<commons-lang3.version>3.3.2</commons-lang3.version>
	<commons-io.version>1.3.2</commons-io.version>
	<commons-net.version>3.3</commons-net.version>
	<commons-fileupload.version>1.3.1</commons-fileupload.version>
</properties>

 	<dependencies>
	<!-- Apache工具元件 -->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>${commons-lang3.version}</version>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-io</artifactId>
		<version>${commons-io.version}</version>
	</dependency>
	<dependency>
		<groupId>commons-net</groupId>
		<artifactId>commons-net</artifactId>
		<version>${commons-net.version}</version>
	</dependency>
	<!-- Spring -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-beans</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aspects</artifactId>
		<version>${spring.version}</version>
	</dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context-support</artifactId>
           <version>${spring.version}</version>
       </dependency>
	<!-- JSP相關 -->
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>${jstl.version}</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>${servlet-api.version}</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jsp-api</artifactId>
		<version>${jsp-api.version}</version>
		<scope>provided</scope>
	</dependency>
	<!-- 檔案上傳元件 -->
	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>${commons-fileupload.version}</version>
	</dependency>
       <dependency>
           <groupId>com.github.kischang</groupId>
           <artifactId>fastdfs-client</artifactId>
           <version>0.1</version>
       </dependency>
</dependencies>
新增Tomcat的外掛:
<build>
       <pluginManagement>
           <plugins>
               <!-- 配置Tomcat外掛 -->
               <plugin>
                   <groupId>org.apache.tomcat.maven</groupId>
                   <artifactId>tomcat7-maven-plugin</artifactId>
                   <version>2.2</version>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>
3、配置Spring MVC

  在resources包下新增一個資料夾spring,在spring資料夾下建立xml檔案,配置Spring MVC的相關內容,如下:

<?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.tgb.fastdfs" />
	<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>
4、配置web.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

	<!-- 解決post亂碼 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- springmvc的前端控制器 -->
	<servlet>
		<servlet-name>fastdfs</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置檔案預設在:WEB-INF/servlet的name+"-servlet.xml" -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>fastdfs</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
5、編寫程式碼

  首先是Controller類:

package com.tgb.fastdfs;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class UploadFiles {

	@RequestMapping("upload")
	public String toUpload() {
		return "upload";
	}

	@RequestMapping(value = "media/uploadVideo", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public void uploadVideo(HttpServletRequest request,
	        HttpServletResponse response) throws Exception {

		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> names = multiRequest.getFileNames();
		String filename = "";
		while (names.hasNext()) {
			String name = names.next();
			List<MultipartFile> fileList = multiRequest.getFiles(name);
			for (MultipartFile file : fileList) {
				filename = file.getOriginalFilename();
				String fileext = filename.substring(filename.indexOf(".") + 1);
				String id = DfsUtil.uploadFile(file.getBytes(), fileext);
				String url = DfsUtil.getFullUrl(id);
				System.out.println(filename);
				System.out.println(id);
				System.out.println(url);
			}
		}
	}
}
工具類DfsUtil:
package com.tgb.fastdfs;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class DfsUtil {

	private static Properties config = new Properties();

	private static StorageClient1 storageClient1 = null;

	static {
		// 初始化讀配置檔案
		try {
			String dfsProp = "D:\\my-program\\webservice\\fastdfs\\target\\classes\\fastdfs\\dfs.properties";
			InputStream in = new BufferedInputStream(new FileInputStream(
			        dfsProp));
			config.load(in);
		} catch (Exception e) {
			System.out.println("初始化配置檔案錯誤");
		}
		// 初始化連線池
		try {
			String confPath = "D:\\my-program\\webservice\\fastdfs\\target\\classes\\fastdfs\\dfs.properties";
			ClientGlobal.init(confPath);
			TrackerClient trackerClient = new TrackerClient(
			        ClientGlobal.g_tracker_group);
			TrackerServer trackerServer = trackerClient.getConnection();
			if (trackerServer == null) {
				throw new IllegalStateException("getConnection return null");
			}

			StorageServer storageServer = trackerClient
			        .getStoreStorage(trackerServer);
			if (storageServer == null) {
				throw new IllegalStateException("getStoreStorage return null");
			}

			storageClient1 = new StorageClient1(trackerServer, storageServer);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getFullUrl(String id) {
		String domain = config.getProperty("domain");
		return domain + id;
	}

	public static String getThumbUrl(String id, Integer width, Integer height) {
		String domain = config.getProperty("domain");
		String name = id.substring(0, id.lastIndexOf("."));
		String suf = id.substring(id.lastIndexOf("."), id.length());
		StringBuilder url = new StringBuilder(domain);
		url.append(name);
		url.append("_");
		url.append(width);
		url.append("x");
		url.append(height);
		url.append(suf);
		return url.toString();
	}

	public static String uploadFile(byte[] file_buff, String file_ext_name)
	        throws Exception {
		return storageClient1.upload_file1(file_buff, file_ext_name, null);
	}

	public static Boolean deleteFile(String id) throws Exception {
		int result = storageClient1.delete_file1(id);
		if (result == 0) {
			return true;
		} else {
			return false;
		}
	}
}
6、配置fastdfs的配置檔案

  在電腦盤中建立一個路徑,然後建立一個properties檔案(Demo中的路徑是:D:\\my-program\\webservice\\fastdfs\\target\\classes\\fastdfs\\dfs.properties)配置如下內容:

connect_timeout = 30
network_timeout = 60
charset = ISO8859-1
http.tracker_http_port = 8090
http.anti_steal_token = no
http.secret_key = 123456
tracker_server = 192.168.**.252:22122
domain=http://192.168.**.252/
7、建立JSP

  使用input type為file的控制元件上傳檔案,用ajax向後臺提交

<input type="file" id="file" name="file"  style="width: 180px;" onchange="uploadFile(this)" />
<input type="text" id="videoFileId" style="border: none;display:none;width:20%;" onclick="this.style.display='none';document.getElementById('file').style.display='';">
<input type="hidden" id="videoType" name="imageType"/>
JS方法:
function uploadFile(formTag){
    var fileInput = document.getElementById("file");
    var videoInput = document.getElementById("videoFileId");
    var filename=fileInput.value;
    var uploadFileName=filename.substring(filename.lastIndexOf("\\")+1,filename.length);
    var url = '<%=path%>' + "/media/uploadVideo";
    $.ajaxFileUpload({
        url : url,
        type:"Post",
        dataType:'json',
        fileElementId : "file",// 檔案選擇框的id屬性
        success : function(data, status) {
            $(videoInput).css("display","");
            document.getElementById("file").style.display="none";
            videoInput.value=uploadFileName;
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            $(videoInput).css("display","none");
            fileInput.style.display="";
            $.alert({
                title: '溫馨提示',
                content: "上傳失敗!",
                confirmButton: '確定',
                confirmButtonClass: 'btn-primary',
                animation: 'scale',
                confirm: function () {
                }
            });
        }
    });
}
8、啟動專案

  使用maven build,輸入命令clean tomcat7:run即可啟動專案。啟動成功後訪問頁面,選擇要上傳的檔案,如果後臺打印出以下內容,即檔案上傳成功。