WEB应用中使用 FastDFS
1 依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.bjsxt</groupId>
<artifactId>upload-fdfs</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>cn.bestwu</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis 整合 spring 插件 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
2 数据库建模
drop table if exists t_files;
create table t_files(
id bigint not null auto_increment,
file_name varchar(255), -- 文件的原始名称
group_name varchar(32), -- 文件在 FastDFS 中的卷名
remote_file_name varchar(255), -- 文件在 FastDFS 中的文件名, UUID
file_path varchar(255), -- 文件在 FastDFS 中的路径, 就是卷名+远程文件名
primary key(id)
);
3 FastDFS 配置
connect_timeout = 10
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8080
tracker_server = 192.168.89.152:22122
4 Spring 配置
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.bjsxt"></context:component-scan>
<!-- 文件上传的转换器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制文件上传大小 -->
<property name="maxUploadSize" value="2048000" />
<!-- 内存缓存大小 -->
<property name="maxInMemorySize" value="2048" />
<!-- 处理文本文件的字符集 -->
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- 连接池数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/fdfsfile" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- 会话工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations">
<array>
<value>classpath:com/bjsxt/mapper/*.xml</value>
</array>
</property>
</bean>
<!-- Mapper 工厂 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.bjsxt.mapper" />
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!-- 事务切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution( * com.bjsxt.service.*.*(..))"/>
</aop:config>
</beans>
5 web.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>/index</welcome-file>
</welcome-file-list>
<filter>
<filter-name>charsetFilter</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>charsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
6 FastDFS 工具类定义
package com.bjsxt.fdfs;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
// FastDFS 的工具类
public class FastDFSCommonsUtils {
private static StorageClient storageClient = null;
static{
try{
ClientGlobal.init(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"test/fdfs.conf");
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
storageClient = new StorageClient(trackerServer, storageServer);
}catch(Exception e){
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
/**
* 上传文件的方法
* @param inputStream 要上传的文件的输入流,用于读取文件内容
* @param fileName 要上传的文件的原始文件名
* @return 上传的结果
*/
public static String[] upload(InputStream inputStream, String fileName){
try {
NameValuePair[] metaList = new NameValuePair[]{
new NameValuePair("fileName", fileName)
};
String extFileName = fileName.substring(fileName.lastIndexOf(".") + 1);
byte[] datas = new byte[inputStream.available()];
inputStream.read(datas);
String[] result = storageClient.upload_file(datas, extFileName, metaList);
return result;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 下载文件
* @return 要下载的文件的输入流
*/
public static InputStream download(String groupName, String remoteFileName){
try{
byte[] datas = storageClient.download_file(groupName, remoteFileName);
return new ByteArrayInputStream(datas);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
7 实体类型
package com.bjsxt.entity;
import java.io.Serializable;
import java.util.Objects;
// 文件相关信息的实体类
public class FileInfo implements Serializable {
private Long id;
private String fileName;
private String groupName;
private String remoteFileName;
private String filePath;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FileInfo fileInfo = (FileInfo) o;
return Objects.equals(id, fileInfo.id) &&
Objects.equals(fileName, fileInfo.fileName) &&
Objects.equals(groupName, fileInfo.groupName) &&
Objects.equals(remoteFileName, fileInfo.remoteFileName) &&
Objects.equals(filePath, fileInfo.filePath);
}
@Override
public int hashCode() {
return Objects.hash(id, fileName, groupName, remoteFileName, filePath);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getRemoteFileName() {
return remoteFileName;
}
public void setRemoteFileName(String remoteFileName) {
this.remoteFileName = remoteFileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
8 Mapper 接口定义
package com.bjsxt.mapper;
import com.bjsxt.entity.FileInfo;
import java.util.List;
// 文件数据的数据访问接口
public interface FileInfoMapper {
/**
* 新增文件相关数据到数据库
* @param fileInfo 要新增的数据
*/
void insertFileInfo(FileInfo fileInfo);
/**
* 查询所有的文件相关数据
* @return
*/
List<FileInfo> selectFileInfos();
/**
* 主键查询详情
* @param id
* @return
*/
FileInfo selectById(Long id);
}
9 Mapper 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.FileInfoMapper">
<insert id="insertFileInfo">
insert into t_files(id, file_name, group_name, remote_file_name, file_path)
values(default, #{fileName}, #{groupName}, #{remoteFileName}, #{filePath})
</insert>
<select id="selectFileInfos" resultType="com.bjsxt.entity.FileInfo">
select id, file_name as fileName, group_name as groupName, remote_file_name as
remoteFileName,
file_path as filePath
from t_files
</select>
<select id="selectById" resultType="com.bjsxt.entity.FileInfo">
select id, file_name as fileName, group_name as groupName, remote_file_name as
remoteFileName,
file_path as filePath
from t_files
where id = #{id}
</select>
</mapper>
10 服务接口
package com.bjsxt.service;
import com.bjsxt.entity.FileInfo;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;
// 文件处理服务接口
public interface FileService {
/**
* 上传文件到 FastDFS 中,把文件的一些相关数据保存到数据库中。
* @param file - 要上传的文件
* @return true - 成功 ; false - 失败
*/
boolean uploadFile(MultipartFile file);
/**
* 查询所有的可下载的文件的数据
* @return 数据库中的数据集合
*/
List<FileInfo> getFileInfos();
/**
* 获取要下载的文件
* @param fileInfoId 文件在数据库中的主键
* @return 要下载的文件的输入流
*/
InputStream getFile(Long fileInfoId);
FileInfo getFileInfoById(Long fileInfoId);
}
11 服务实现
package com.bjsxt.service.impl;
import com.bjsxt.entity.FileInfo;
import com.bjsxt.fdfs.FastDFSCommonsUtils;
import com.bjsxt.mapper.FileInfoMapper;
import com.bjsxt.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
// 文件处理服务实现
@Service
public class FileServiceImpl implements FileService {
@Autowired
private FileInfoMapper fileInfoMapper;
@Override
public boolean uploadFile(MultipartFile file) {
try {
String[] result = FastDFSCommonsUtils.upload(file.getInputStream(),
file.getOriginalFilename());
if(result == null){
// 上传失败
return false;
}
// System.out.println(Arrays.toString(result));
// 将文件相关信息保存到数据库
FileInfo fileInfo = new FileInfo();
fileInfo.setFileName(file.getOriginalFilename());
fileInfo.setGroupName(result[0]);
fileInfo.setRemoteFileName(result[1]);
fileInfo.setFilePath(result[0]+"/"+result[1]);
this.fileInfoMapper.insertFileInfo(fileInfo);
return true;
}catch (Exception e){ // 上传失败
e.printStackTrace();
return false;
}
}
@Override
public List<FileInfo> getFileInfos() {
return this.fileInfoMapper.selectFileInfos();
}
@Override
public InputStream getFile(Long fileInfoId) {
// 访问数据库,获取要下载的文件的详情信息
FileInfo fileInfo = this.fileInfoMapper.selectById(fileInfoId);
// 访问 FastDFS,获取要下载的文件的具体内容
InputStream inputStream =
FastDFSCommonsUtils.download(fileInfo.getGroupName(), fileInfo.getRemoteFileName());
// 返回
return inputStream;
}
@Override
public FileInfo getFileInfoById(Long fileInfoId) {
return this.fileInfoMapper.selectById(fileInfoId);
}
}
12 控制器
package com.bjsxt.controller;
import com.bjsxt.entity.FileInfo;
import com.bjsxt.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
// 文件控制器,实现上传、下载功能
@Controller
public class FileController {
@Autowired
private FileService fileService;
/**
* 文件上传
* @param uploadFile 要上传的文件
* @return
*/
@RequestMapping("/uploadFile")
public String uploadFile(MultipartFile uploadFile){
// System.out.println("上传文件的原始名称 - " + uploadFile.getOriginalFilename());
// System.out.println("上传文件的大小 - " + uploadFile.getSize());
// 上传文件到 FastDFS 中
boolean flag = this.fileService.uploadFile(uploadFile);
System.out.println(flag ? "上传成功" : "上传失败");
return "redirect:/index";
}
/**
* 进入到首页面的方法。
* 在进入首页面之前,需要先访问数据库,查询可以下载的文件的相关信息。
* @return
*/
@RequestMapping(value = {"/", "/index"})
public String toIndex(Model model){
List<FileInfo> list = this.fileService.getFileInfos();
model.addAttribute("list", list);
return "forward:/index.jsp";
}
/**
* 下载文件
* @param fileInfoId 要下载的文件在数据库中的相关数据主键
*/
@RequestMapping(value="/downloadFile/{fileInfoId}")
public void downloadFile(@PathVariable("fileInfoId") Long fileInfoId, HttpServletResponse
response){
// 获取要传递给客户端的文件数据
InputStream inputStream = null;
try {
inputStream = this.fileService.getFile(fileInfoId);
FileInfo fileInfo = this.fileService.getFileInfoById(fileInfoId);
// 设置响应头, 响应为下载,下载的文件名是什么
response.setContentType("application/octet-stream");
response.setHeader("content-disposition",
"attachement;filename="+fileInfo.getFileName());
// 通过输出流输出文件内容到客户端
OutputStream outputStream = response.getOutputStream();
byte[] temp = new byte[512];
int len = 0;
while((len = inputStream.read(temp)) != -1){
outputStream.write(temp, 0, len);
}
// 刷新缓存
outputStream.flush();
}catch(Exception e){
e.printStackTrace();
}finally {
if(inputStream != null){ // 回收资源
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
13 页面 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>FastDFS WEB 应用</title>
</head>
<body>
<center>
<form method="post" enctype="multipart/form-data" action="/uploadFile">
选择要上传的文件:<input type="file" name="uploadFile">
<input type="submit" value="上传">
</form>
<table border="1" style="width: 800px">
<thead>
<tr>
<th>文件原始名称</th>
<th>文件卷标名称</th>
<th>文件远程名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="fileInfo">
<tr>
<th>${fileInfo.fileName}</th>
<th>${fileInfo.groupName}</th>
<th>${fileInfo.remoteFileName}</th>
<th><a href="/downloadFile/${fileInfo.id}"> 下 载
</a> <a href="http://192.168.89.153:8888/${fileInfo.filePath}"
target="_blank">预览</a></th>
</tr>
</c:forEach>
</tbody>
</table>
</center>
</body>
</html>