使用FastDFS上传一张图片

一.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
        });
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值