前言:

现在的项目过于大且并发量高,大多都是用负载均衡的来管理。拿电商项目来讲,商品的图片太多,一台服务器明显是不行的,所以要用到FastDFS做集群,来解决图片存储空间扩容问题。在项目中,要多出用到上传图片的方法,所以在此封装了一个上传类,仅供参考。
封装类:

public class PmsUploadUtil {

    public static String uploadImage(MultipartFile multipartFile) {
        String imgUrl="http://192.168.188.146";(自己的站点或者Ip)
        //上传图片到服务器
        //配置fdfs的全局链接地址
        String tracker = PmsUploadUtil.class.getResource("/tracker.conf").getPath();//获取配置文件路径
        try {
            ClientGlobal.init(tracker);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        TrackerClient trackerClient = new TrackerClient();
        //获得一个tackerservice的实例
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过tracker获得一个storage客户端
        StorageClient storageClient = new StorageClient(trackerServer,null);

        try {
            byte[] bytes = multipartFile.getBytes();//获得上传的二进制对象
            //获得文件后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            System.out.println(originalFilename);
            int i = originalFilename.lastIndexOf(".");
            String extName=originalFilename.substring(i+1);
            String[]  uploadInfos = storageClient.upload_file(bytes, "jpg", null);
            for (String uploadInfo : uploadInfos) {
                imgUrl+="/"+uploadInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgUrl;
    }
}
Last modification:October 24th, 2019 at 11:48 pm
如果觉得我的文章对你有用,请随意赞赏