FastDFS上传简单Demo
FastDFS是一个轻量级的分布式文件系统,它对文件的管理功能包括:文件存储、文件同步、文件访问等,解决了大容量存储和负载均衡的问题。下面是Demo的代码,采用的是Spring MVC框架。 开发工具:Eclipsejar包管理:MavenJDK:1.8 1、首先创建Maven项目 File-->New-->Project-->Maven Pro..
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即可启动项目。启动成功后访问页面,选择要上传的文件,如果后台打印出以下内容,即文件上传成功。
更多推荐
所有评论(0)