一、资源准备
FastDFS安装配置请参考:https://blog.csdn.net/weixin_44187730/article/details/85951370
1):由于FastDFS客户端jar包并没有在中央仓库中,所以需要使用下列命令手动安装jar包到Maven本地仓库
mvn install:install-file -DgroupId=org.csource.fastdfs -DartifactId=fastdfs -Dversion=1.2 -Dpackaging=jar -Dfile=F:\fastdfs_client_v1.20.jar
2):pom.xml里加入需要的依赖
< dependency>
< groupId> org.csource.fastdfs</ groupId>
< artifactId> fastdfs</ artifactId>
< version> 1.2</ version>
</ dependency>
< dependency>
< groupId> commons-io</ groupId>
< artifactId> commons-io</ artifactId>
< version> 2.5</ version>
</ dependency>
< dependency>
< groupId> commons-fileupload</ groupId>
< artifactId> commons-fileupload</ artifactId>
< version> 1.3.2</ version>
</ dependency>
3):在/resources/config创建配置文件
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=/opt/module/FastDFS/repo/tracker
# tracker_server can ocur more than once, and tracker_server format is
# "host:port", host can be hostname or ip address
tracker_server=127.0.0.1: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
application.properties(Nginx服务器下载地址)
#nginx文件下载地址
FILE_SERVER_URL=http://127.0.0.1:8888/
4):配置spring-mvc.xml文件解析器、并加载application.properties配置文件
< context: property-placeholder location = " classpath:config/application.properties" />
< bean id = " multipartResolver" class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" >
< property name = " defaultEncoding" value = " utf-8" />
< property name = " maxUploadSize" value = " 52428800" />
</ bean>
二、FastDFS文件上传工具类封装
package com. hf. utils ;
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 FastDFSClientUtils {
private TrackerClient trackerClient = null ;
private TrackerServer trackerServer = null ;
private StorageServer storageServer = null ;
private StorageClient1 storageClient = null ;
public FastDFSClientUtils ( 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) ;
}
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 ) ;
}
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 ) ;
}
}
三、文件上传
1): 后台请求处理代码
package com. hf. fastdfs. controller ;
import com. hf. utils. FastDFSClientUtils ;
import org. springframework. beans. factory. annotation. Value ;
import org. springframework. web. bind. annotation. GetMapping ;
import org. springframework. web. bind. annotation. PostMapping ;
import org. springframework. web. bind. annotation. RestController ;
import org. springframework. web. multipart. MultipartFile ;
@RestController
public class UploadController {
@Value ( "${FILE_SERVER_URL}" )
private String file_server_url;
@PostMapping ( "/upload" )
public Object upload ( MultipartFile file) {
String originalFilename = file. getOriginalFilename ( ) ;
String extName = originalFilename. substring ( originalFilename. lastIndexOf ( "." ) + 1 ) ;
try {
FastDFSClientUtils clientUtils = new FastDFSClientUtils ( "classpath:config/fdfs_client.conf" ) ;
String fileId = clientUtils. uploadFile ( file. getBytes ( ) , extName) ;
String url = file_server_url + fileId;
return MsgUtils . success ( ) . add ( "url" , url) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
return MsgUtils . fail ( ) ;
}
}
}
2): 前端代码(angular发送文件上传请求)
app. service ( 'uploadService' , function ( $http ) {
this . uploadFile = function ( ) {
let formData = new FormData ( ) ;
formData. append ( 'file' , file. files[ 0 ] ) ;
return $http ( {
url : '/upload' ,
method : 'POST' ,
data : formData,
headers : { 'Content-Type' : undefined } ,
transformRequest : angular. identity
} ) ;
} ;
} ) ;
app. controller ( 'uploadController' , [ '$scope' , '$http' , 'uploadService' , function ( $scope, $http, uploadService ) {
$scope. uploadFile = function ( ) {
uploadService. uploadFile ( )
. then ( result => {
console. log ( result) ;
} , ( result ) => {
console. log ( result) ;
} ) ;
} ;
} ] ) ;
< form role = " form" enctype = " multipart/form-data" >
< div class = " form-group" >
< label> 选择文件</ label>
< input type = " file" class = " form-control" name = " file" >
</ div>
< button class = " btn btn-primary" type = " button" ng-click = " uploadFile()" > 开始上传</ button>
</ form>
效果图