fastDFS 파일 업로드 완료
35126 단어 ZTBest
그림 서버 구축 완료 파일 업로드:
1. Tracker 클러스터
1.
2.
2. Storage 클러스터 + 분산
: ( )
: ( , )
3. 개발 절차
3.1 도입 의존
<dependency>
<groupId>org.csource.fastdfsgroupId>
<artifactId>fastdfsartifactId>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
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 멀티미디어 해상도 중점 설정
<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>WriteMapNullValuevalue>
<value>WriteDateUseDateFormatvalue>
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>
<property name="maxUploadSize" value="5242880">property>
bean>
<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);
}
/**
*
* Title: uploadFile
* Description:
* @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);
}
/**
*
* Title: uploadFile
* Description:
* @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
});
}
});