fastDFS完成文件上传

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 18:36   45   0

搭建图片服务器完成文件上传:

1.Tracker集群
1.心跳检测机制
2.选举机制
2.Storage集群 + 分布式
集群: 多台服务器干同一件事(一个挂了不影响另一个)
分布式: 多台服务器共同完成一件事(一台服务器的内存不够, 用另外一台)

3.开发步骤

3.1 引入依赖
<dependency>
 <groupId>org.csource.fastdfs</groupId>
 <artifactId>fastdfs</artifactId>
</dependency>
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
</dependency>
3.2 fastDFS配置文件: fdfs_client.conf
# 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.25.133: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
3.3 springmvc配置文件: 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:dubbo="http://code.alibabatech.com/schema/dubbo" 
 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.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
     
    <context:property-placeholder location="classpath:config/application.properties" />
 
 <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>WriteMapNullValue</value>
           <value>WriteDateUseDateFormat</value>
         </array>
       </property>
     </bean>
   </mvc:message-converters>  
 </mvc:annotation-driven>
 
 <!-- 配置多媒体解析器 -->
 <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>
 
 <!-- 引用dubbo 服务 -->
 <dubbo:application name="oranges-shop-web" />
 <dubbo:registry address="zookeeper://192.168.25.135:2181"/>
 <dubbo:annotation package="com.oranges.shop.controller" />   
</beans>
3.4 文件上传工具类: FastDFSClient.java
package util;

import org.csource.common.NameValuePair;
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 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);
 }
 
 /**
  * 上传文件方法
  * <p>Title: uploadFile</p>
  * <p>Description: </p>
  * @param fileName 文件全路径
  * @param extName 文件扩展名,不包含(.)
  * @param metas 文件扩展信息
  * @return
  * @throws Exception
  */
 public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
  String result = storageClient.upload_file1(fileName, extName, metas);
  return result;
 }
 
 public String uploadFile(String fileName) throws Exception {
  return uploadFile(fileName, null, null);
 }
 
 public String uploadFile(String fileName, String extName) throws Exception {
  return uploadFile(fileName, extName, null);
 }
 
 /**
  * 上传文件方法
  * <p>Title: uploadFile</p>
  * <p>Description: </p>
  * @param fileContent 文件的内容,字节数组
  * @param extName 文件扩展名
  * @param metas 文件扩展信息
  * @return
  * @throws Exception
  */
 public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
  
  String result = storageClient.upload_file1(fileContent, extName, metas);
  return result;
 }
 
 public String uploadFile(byte[] fileContent) throws Exception {
  return uploadFile(fileContent, null, null);
 }
 
 public String uploadFile(byte[] fileContent, String extName) throws Exception {
  return uploadFile(fileContent, extName, null);
 }
}
3.5 文件上传代码实现: UploadController.java
package com.oranges.shop.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import entity.Result;
import util.FastDFSClient;

@RestController
@RequestMapping("/upload")
public class UploadController {
 
 @Value("${FILE_SERVER_URL}")
 private String file_server_url;
 
 @RequestMapping("/uploadFile")
 public Result uploadFile(MultipartFile file){
  
  try {
   // 获得文件名:
   String fileName = file.getOriginalFilename();
   // 获得文件的扩展名:
   String extName = fileName.substring( fileName.lastIndexOf(".")+1 );
   // 创建工具类
   util.FastDFSClient client = new FastDFSClient("classpath:fastDFS/fdfs_client.conf");
   // 返回图片服务器的
   String path = client.uploadFile(file.getBytes(), extName); // group1/M00/
   // 图片服务器中文件的路径
   String url = file_server_url + path;
   
   return new Result(true, url);
  } catch (Exception e) {
   e.printStackTrace();
   return new Result(false, "上传失败!");
  }  
 }
}
3.6 前端代码
app.service("uploadService",function($http){
 
 this.uploadFile = function(){
  // 向后台传递数据: html5的特性
  var formData = new FormData();
  // 向formData中添加数据:
        // "file"与后台保持一致
        // file.files[0]: file前台上传的input的id
  formData.append("file",file.files[0]);
  
  return $http({
   method:'post',
   url:'../upload/uploadFile.do',
   data:formData,
            // 取消angularJS默认的提交json的方式
   headers:{'Content-Type':undefined} ,// Content-Type : text/html  text/plain
   // 将二进制文件序列化
            transformRequest: angular.identity
  });
 }
});
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP