前后端FastDfs文件上传

59 阅读1分钟

1.application配置

#fastdfs配置
fdfs.so-timeout=20000
fdfs.connect-timeout=20000
fdfs.tracker-list=127.0.0.1:8080
#连接支持最大数量
fdfs.pool.max-total=200
#单个tracker最大连接数
fdfs.pool.max-wait-mills=20000
#修改文件上传大小限制
spring.servlet.nultipart.max-file=size=200MB
spring.servlet.nultipart.max-request-size=200MB

2.FastDfsClient.java

public class FastDfsClient{
    @Resource
    private TrackerClient trackerClient;
    
    @Resource
    private FdfsConnectionManager fdfsConnectionManger;
    
    private FastFileStorageClient fastFileStorageClient;
    
    public FastDfsCliuet(FastFileStorageClient fastFileStorageClient) {
        this.fastFileStorageClient = fastFileStorageClient;
    }
    /*文件上传*/
    public StorePath upload(File file) {
        try{
            if(file ==null || !file.exists()){
                throw new IllegalArgumentException("文件不存在");
            }
            String extName = file.getName().substring(file.getName().lastIndexOf(".")+1);
            @Cleanup FileInputStream fileInputStream = new FileInputStream(file);
            StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, file.length(), extName, null);
            logger.info("上传文件:{}成功. group={}, path={}", file.getName(), storePath.getGroup(), storePath.getPath());
            return storePath;
        } catch (Exception e) {
            logger.error("上传失败", e);
            return null;
        }
    }
    /*文件批量上传*/
    public Map<String, StorePath> upload(List<File> files) {
        Map<String, StorePath> map = new HashMap<>(16);
        files.forEach(file -> {
            StorePath upload = upload(file);
            if(upload != null) {
                map.put(file.getName(), upload);
            }
        })
        return map;
    }
    /*文件下载*/
    public byte[] downloadFile(String groupName, String path){
        if(path.startsWith(goup + "/")){
            path = path.split(groupName + "/")[1];
        }
        try {
            StorageNodeInfo fetchStorage = trackerClient.getFetchStorage(groupName, path);
            DownloadByteArray callback = new DownloadByteArray();
            StorageDownloadCommand<byte []> command = new StorageDownloadCommand<>(groupName, path, 0, 0, callback);
            return fdfsConnectionmanager.executeFdfsCmd(fetchStorage.getIntSocketAddress(), command);
        } catch(RuntimeException e) {
            StorageNodeInfo fetchStorage = trackerClient.getFetchStorage(groupName, path);
            DownloadByteArray callback = new DownloadByteArray();
            StorageDownloadCommand<byte[]> command = new StorageDownloadCommand<>(groupName, path, 0,0,callback);
            return fdfsConnectionManager.excuteFdfsCmd(fetchStorage.getInetSocketAddress(), command);
        } catch(Exception e) {
             return null;
        }
    }
    /*文件删除*/
    public void deleteByStorePath(string groupName, String path) {
        fastFileStorageClient.deleteFile(goupName, path);
    }
}

3.文件上传

3.1 前端vue2

<el-dialog title="上传文件" :visible.sync = "uplloadFileShow" :append-to-body="true">
    <el-upload class="upload-el-dia-contain" ref="upload" drag :http-request="httpRequest" :on-change="fileChange" :file-list="uploadFileList" auto-upload="false"> 
        <el-button size="small" type="primary" @click="myFileUpload(dialogFileInfo), (uploadFileShow = false)">
            点击上传
        </el-button>
    </el-upload>
</el-dialog>
export default {
    data() {
        return {
            uploadFileList:[], // 上传文件列表
            // 暂存区:点击查看,动态传输file的
            dialogFileInfo: {
                fileId:"",
                fdfsGroup: "",
                fdfsPath: "",
                fdfsName: "",
                fdfsSize: ""
            },
        }
    },
    methods: {
        // param是自带参数。this.$refs.upload.submit()会自动调用httpRequest方法,在里面取得file
        httpRequest(param) {
            this.fileData.append("file", param.file);
        },
        fileChange(file, fileList) {
            // fileList是文件列表发生变化后,返回的修改后的列表对象
            this.uploadFileList = fileList;
        },
        // 文件上传
        myFileUpload() {
            // FormData对象,用以将数据编译呈键值对,以便使用XMLHttpRequest来发送数据
            this.fileData = new FormData();
            // 会调用httpRequest(),有多少个文件就会代用多少个httpRequest函数
            this.$refs.upload.submit();
            myRequest.upload(this.fileData).then((res) => {
                // 文件上传成功
            })
        }
    }
}

3.2 后端java

// controller
@PostMapping("")
public myResponse myFileUpload(@RequestParam("file") @Validated MultipartFile multipartFile) {
    return myFileService.myFileUpload(multipartFile);
}

//Impl
@Override
public myResponse myFileUpload(@RequestParam("file") @Validated MultipartFile multipartFile) {
    if (file == null || file.isEmpty()){
        return error;
    }
    // 上传
    StorePath storePath;
    try {
        @Cleanup InputStream inputStream = file.getInputStream();
        storePath = fastDfsClient.upload(inputStream, fileSize, fileName.substring(fileName.lastIndexOf('.') + 1));
        Date nowDate = new Date();
        if(storePath == null) {
            
        } else {
            myRequest.buid();
            myFileHandleMapper.insert(myRequest);
        }
    }
}