一.Demo案例
1.新建maven项目,pom文件中添加依赖
<dependency>
<groupId>cn.bestwu</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27</version>
</dependency>
2.编写conf文件,指明 tracker_server 地址
tracker_server=192.168.64.132:22122
3.编写文件上传类
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException, MyException {
//加载第二步中的配置文件 使用绝对路径或先对路径
ClientGlobal.init("E:/ideawork/FastDFSDemo/src/main/resources/FastDFS.conf");
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new
StorageClient(trackerServer,storageServer);
//上传一张本地的图片,第一个参数是文件路径名,第二个参数是文件后缀,第三个参数是扩展信息
//返回值是storage_server 提供的fileid 可以根据该id找的上传后的图片
String []strs = storageClient.upload_file("C:/Users/Administrator/Desktop/0.png","png",null);
for(String str : strs){
System.out.println(str);
}
}
}
运行结果
访问图片
http://192.168.64.132/group1/M00/00/00/wKhAhF9xvYCAKKqpAACLgUDa9VU388.png
二.对上述步骤进行封装
进行封装后方便调用,上传从前端提交的文件数据
1.封装一个 FastDFSClient 工具类
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);
}
}
2.指定好ip地址,用于上传成功后拼接访问地址 即 ip地址+fileid
FILE_SERVER_URL=http://192.168.64.132/
3.编写conf文件,指明 tracker_server 地址
tracker_server=192.168.64.132:22122
4.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 com.fyj.entity.Result;
import com.fyj.utils.FastDFSClient;
/**
* 文件上传Controller
*
* @author Administrator
*/
@RestController
public class UploadController {
@Value("${FILE_SERVER_URL}")
private String FILE_SERVER_URL;//文件服务器地址
@RequestMapping("/upload")
public Result upload(MultipartFile file) {
//1、取文件的扩展名
String originalFilename = file.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
try {
//2、创建一个 FastDFS 的客户端
FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
//3、执行上传处理
String path = fastDFSClient.uploadFile(file.getBytes(), extName);
//4、拼接返回的 url 和 ip 地址,拼装成完整的 url
String url = FILE_SERVER_URL + path;
return new Result(true, url);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "上传失败");
}
}
}
5.前端使用了angularjs
页面
<input type="file" id="file"/>
<button class="btn btn-primary" type="button" ng-click="uploadFile()">上传
</button>
controller
$scope.uploadFile=function(){
uploadService.uploadFile().success(function(response) {
if(response.success){//如果上传成功,取出url
$scope.image_entity.url=response.message;//设置文件地址
}else{
alert(response.message);
}
}).error(function() {
alert("上传发生错误");
});
};
service
app.service("uploadService",function($http){
this.uploadFile=function(){
var formData=new FormData();
formData.append("file",file.files[0]);
return $http({
method:'POST',
url:"../upload.do",
data: formData,
headers: {'Content-Type':undefined},
transformRequest: angular.identity
});
}
});