FastDFS整合SpringBoot实现图片上传功能

FastDFS简介

FastDFS是淘宝开源的文件服务器,支持文件上传、下载,文件同步和存储。使用分组group存储方式,一个group可以包含多个服务器。只有组里的服务器才会互相通信。并且group支持扩展服务器,也可以增加新的group。使用时可以以业务需求划分不同group,比如说视频存储在video组,图片存储在image组。本文以图片上传为例讲解FastDFS如何实现图片上传。

服务器搭建

参考
linux服务器搭建FastDFS

整合到SpringB

  • 引入Maven依赖
    
            org.csource
            fastdfs-client-java
            1.29-SNAPSHOT
        
  • 配置服务器和超时时间
fdfs.connectTimeout=10
fdfs.networkTimeout=30
fdfs.charset=UTF-8
# 可填写多个,以逗号分隔
fdfs.trackerServerAddress=39.97.120.125:22122
  • FastDFS全局配置
@Configuration
public class FastDFSConfig {

    private static final Logger logger = LoggerFactory.getLogger(FastDFSConfig.class);

    @Value("${fdfs.connectTimeout}")
    private int connectTimeout;

    @Value("${fdfs.networkTimeout}")
    private int networkTimeout;

    @Value("${fdfs.charset}")
    private String charset;

    @Value("${fdfs.trackerServerAddress}")
    private String trackerServerAddress;

    private TrackerGroup getTrackerGroup() throws Exception {
        String[] trackerServers = trackerServerAddress.split(",");
        InetSocketAddress[] tracker_servers = new InetSocketAddress[trackerServers.length];
        for (int i = 0; i < trackerServers.length; i++) {
            String[] parts = trackerServers[i].split(":", 2);
            if (parts.length != 2) {
                throw new Exception("the value of item \"trackerServerAddress\" is invalid, the correct format is host:port");
            }
            tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
        }
        return new TrackerGroup(tracker_servers);
    }

    @Bean
    public TrackerClient trackerClient() {
        try {
            ClientGlobal.setG_connect_timeout(connectTimeout * 1000);
            ClientGlobal.setG_network_timeout(networkTimeout * 1000);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_tracker_group(getTrackerGroup());
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
            logger.info("FastDFS - TrackerClient inited");
            return trackerClient;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

}

文件上传功能

    public String uploadHead(MultipartFile file, String fileExtName) {
        long time = System.currentTimeMillis();
        String[] result = null;
        File newFile = null;
        try {
            byte[] file_buff;
            newFile = FileUtil.resizeImage(file);
            InputStream inputStream = new FileInputStream(newFile);
            int len = inputStream.available();
            file_buff = new byte[len];
            inputStream.read(file_buff);
            result = getImageClient().upload_file(file_buff, fileExtName, null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        time = System.currentTimeMillis() - time;
        logger.info("Upload head: {} Cost: {}ms", file.getOriginalFilename(), time);
        if (newFile != null) newFile.delete();   //删除临时文件
        if (result != null)
            return result[1];
        return null;
    }
}

前端图片的上传

HTML


;

JS
  1. 获取file输入框
 var file1 = document.getElementById('optionA');
           manageEditContestProblemPage.getImage1(file1);
  1. 对文件进行读写
    getImage1:function(File){
        var file =File.files[0];
        if(undefined == file){
            return ;
        }
        var res='';
        var r = new FileReader();
        r.readAsDataURL(file);
        r.onload = function(e) {
            img1= convertBase64UrlToBlob(e.target.result);
        }

    }
  1. 转化为Blob
function convertBase64UrlToBlob(urlData) {

    var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头,并转换为byte

    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }

    return new Blob([ab], {type: 'image/jpeg'});
}
  1. 发送ajax请求
  var formData = new FormData();//formdata封装Blob文件以及其他字段

        formData.append('file1', img1, optionA); 
         $.ajax({
                url : app.URL.addQuestionUrl(),
                type : "POST",
                dataType: "json",
                //contentType : "application/json;charset=UTF-8",
                processData: false, // 告诉jQuery不要去处理发送的数据
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                
                data : formData,
                success:function(result) {
                    if (result && result['success']) {
                        // 验证通过 刷新页面
                        window.location.reload();
                    } else {
                        $('#loginModalErrorMessage').html('
错误提示
\n' + '

'+result.message+'

'); $('#loginModalErrorMessage').removeClass('hidden'); } }, error:function(result){ $('#loginModalErrorMessage').html('
错误提示
\n' + '

'+result.message+'

'); $('#loginModalErrorMessage').removeClass('hidden'); } });

后端接收请求

 @RequestMapping(value="/api/addQuestion", method= RequestMethod.POST)

    public AjaxResult addQuestion(HttpServletRequest request, HttpServletResponse response, Question question
            , @RequestParam(required = false) MultipartFile file1
            ) {
        AjaxResult ajaxResult = new AjaxResult();
        if(file1!=null) {
            String fileExtName;
            if ((fileExtName = FileUtil.isImg(file1)) == null)
                return new AjaxResult();
            String fileName = fileService.uploadHead(file1, fileExtName);
            if (fileName == null)
                return new AjaxResult();
           question.setOptionA(fileName);
        }
    }

具体代码地址待更

你可能感兴趣的:(FastDFS整合SpringBoot实现图片上传功能)