go-fastdfs 上传文件终极篇

go-fastdfs已经搭建完成
那么开始java代码,走起:
准备工作:
yml 配置文件

dfs:
  ip: xxxxx
  port: 8080

1.首先建立一个文件上传工具类

package com.zyw.shows.util;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.zyw.shows.entity.PageData;
import com.zyw.shows.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

@Component
public class FileFastDfs {

    @Value("${dfs.ip}")
    public String ip;

    @Value("${dfs.port}")
    public String port;

    @Autowired
    FileMapper fileMapper;


    /**
     * 文件上传到dfs服务器
     * @param file
     * @param dir
     * @return
     */
    public PageData uploadFile(MultipartFile file, String dir) {
//        File file1 = null;
        InputStreamResource isr = null;
        try {
//            file1 = multipartFileToFile(file);
            isr=new InputStreamResource(file.getInputStream(),
                    file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //文件地址
        //声明参数集合
        HashMap<String, Object> paramMap = new HashMap<>();
        //文件
        paramMap.put("file", isr);
        //输出
        paramMap.put("output", "json");
        //自定义路径
        paramMap.put("path", dir);
        //场景
        System.err.println(file.getName());
        paramMap.put("scene", file.getName().substring(file.getName().lastIndexOf(".") + 1));

        paramMap.put("fileName", System.currentTimeMillis() + "" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        System.err.println(paramMap);
        //
        String result = HttpUtil.post("http://" + ip + ":" + port + "/group1/upload", paramMap);
        System.err.println(result);
        PageData pageData = JSONObject.parseObject(result, PageData.class);
        pageData.put("fileName", file.getOriginalFilename());
        fileMapper.insertFile(pageData);
        return pageData;
    }

    /*/**
     * @description: 文件上传到dfs服务器
     * @params  [file:File 文件, dir 文件存放路径]
     * @return: com.speedchina.fusionmap.gccl.domain.base.PageData
     * @author: chqf
     * @time: 2020/3/31 2020/3/31
     */
    public PageData uploadFile(File file, String dir) {
        //文件地址
        //声明参数集合
        HashMap<String, Object> paramMap = new HashMap<>();
        //文件
        paramMap.put("file", file);
        //输出
        paramMap.put("output", "json");
        //自定义路径
        paramMap.put("path", dir);
        //场景
        System.err.println(file.getName());
        paramMap.put("fileName", System.currentTimeMillis() + "" + file.getName().substring(file.getName().lastIndexOf(".")));
        paramMap.put("scene", file.getName().substring(file.getName().lastIndexOf(".") + 1));
        System.err.println(paramMap);
        //上传
        String result = HttpUtil.post("http://" + ip + ":" + port + "/group1/upload", paramMap);
        System.err.println(result);
        PageData pageData = JSONObject.parseObject(result, PageData.class);
        pageData.put("fileName", file.getName());
        fileMapper.insertFile(pageData);
        return pageData;
    }

    /*/**
     * @description: 文件base64流获取
     * @params  [fileName : 文件路径]
     * @return: java.lang.String
     * @author: chqf
     * @time: 2020/3/31 2020/3/31
     */
    public String getBase64(String fileName) {
        if (fileName == null || fileName.equals("")) {
            return "";
        }
        InputStream fis = null;
        URL url = null;
        try {
            url = new URL("http://" + ip + ":" + port + "/" + URLEncoder.encode(fileName,"utf-8"));
            System.err.println(url);
            fis = url.openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        String imgStr = "";
        try {
            if (fis == null) {
                return null;
            }
            int len = -1;
            byte[] buf = new byte[2048];
            while (-1 != (len = fis.read(buf, 0, buf.length))) {
                data.write(buf, 0, len);
            }
            BASE64Encoder encoder = new BASE64Encoder();
            imgStr = encoder.encode(data.toByteArray());
            fis.close();
            data.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "data:image/jpeg;base64," + imgStr;
    }

    /*/**
     * @description: 文件格式转换multipartFil 转为 File 格式
     * @params  [file]
     * @return: java.io.File
     * @author: chqf
     * @time: 2020/3/31 2020/3/31
     */
    public File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*/**
     * @description: 文件base64流获取
     * @params  [fileName : 文件路径]
     * @return: java.lang.String
     * @author: chqf
     * @time: 2020/3/31 2020/3/31
     */
    public Boolean getFile(String fileName,HttpServletResponse response) {
        if (fileName == null || fileName.equals("")) {
            return null;
        }
        InputStream fis = null;
        URL url = null;
        try {
            url = new URL("http://" + ip + ":" + port + "/" + URLEncoder.encode(fileName,"utf-8"));
            System.err.println(url);
            fis = url.openStream();
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = fis.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}


第二步建立完工具类会发现报错 pagedata实体类缺少和mappe文件缺少
(注意我们这里存入库采用了两张表 也就是文件表单独一张,业务和文件关联表单独一张,其实也可以直接文件表然后进行逗号分隔)
(1)PageData实体类:

package com.zyw.shows.entity;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class PageData extends HashMap implements Map{

    private static final long serialVersionUID = -3684941159524409837L;
    private Map map = null;
    private HttpServletRequest request;
    public PageData(HttpServletRequest request){
        this.request = request;
        Map properties = request.getParameterMap();
        Map returnMap = new HashMap();
//        returnMap.put("pageSize",10);
//        returnMap.put("pageNum",1);
        Iterator entries = properties.entrySet().iterator();
        Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for (String value1 : values) {
                    value = value1 + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        map = returnMap;
    }

    public PageData() {
        map = new HashMap();
    }

    @Override
    public Object get(Object key) {
        Object obj = null;
        if(map.get(key) instanceof Object[]) {
            Object[] arr = (Object[])map.get(key);
            obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
        } else {
            obj = map.get(key);
        }
        return obj;
    }

    public String getString(Object key) {
        return (String)get(key);
    }
    public Integer getInteger(Object key) {
        Object val = map.get(key);
        if(val instanceof String){
            return Integer.valueOf(getString(key));
        }else if(val instanceof Integer){
            return (Integer) val;
        }else{
            return 0;
        }
//        return Integer.valueOf(map.get(key).toString());
    }

    @Override
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }

    @Override
    public Object remove(Object key) {
        return map.remove(key);
    }

    public void clear() {
        map.clear();
    }

    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

    public Set entrySet() {
        return map.entrySet();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public Set keySet() {
        return map.keySet();
    }

    public void putAll(Map t) {
        map.putAll(t);
    }

    public int size() {
        return map.size();
    }

    public Collection values() {
        return map.values();
    }

}

(2)mapper 文件

package com.zyw.shows.mapper;

import com.zyw.shows.entity.PageData;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @author zyw
 */
@Repository
@Mapper
public interface FileMapper {
    Boolean insertFile(PageData pageData);
    Boolean insertFileEvent(PageData pageData);
}

(3)mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyw.shows.mapper.FileMapper">
    <insert id="insertFile"  parameterType="com.zyw.shows.entity.PageData">
        INSERT INTO
            s_xtgl_file
                (id,md5, name, path, type, update_time,  operator)
        VALUES
         (#{id},#{md5}, #{fileName}, #{path}, #{scenes}, now(), NULL);
    </insert>
    <insert id="insertFileEvent"  parameterType="com.zyw.shows.entity.PageData">
        INSERT INTO
        b_event_file
        (id, event_id, createtime, file_id)
        VALUES
        (#{id}, #{event_id}, now(), #{file_id});
    </insert>

</mapper>

(4)数据库
CREATE TABLE s_xtgl_file (
id varchar(11) NOT NULL,
name varchar(255) DEFAULT NULL,
path varchar(255) DEFAULT NULL,
type varchar(255) DEFAULT NULL,
update_time timestamp NULL DEFAULT NULL,
desc varchar(255) DEFAULT NULL,
operator varchar(255) DEFAULT NULL,
md5 varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE b_event_file (
id varchar(255) NOT NULL COMMENT ‘主键’,
event_id varchar(255) DEFAULT NULL COMMENT ‘事件id’,
createtime timestamp NULL DEFAULT NULL COMMENT ‘上传时间’,
file_id varchar(255) DEFAULT NULL COMMENT ‘文件id’,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
三,准备结束完毕 开始调用
剖析 文件进入 file字段watch的结果
在这里插入图片描述
在这里插入图片描述

     /**
     * 上传文件到go-fastdfs服务器上(调用工具类上传,注意工具类里面本身就有存入数据库服务的语句)
     * @param map
     * @param file
     * @return
     */
    @PostMapping(value = "/insertFile")
    public String updownload(@RequestParam Map<String,Object> map, MultipartFile file){
        PageData pageData=fileFastDfs.uploadFile(file,"/group/zyw");
        String type = pageData.getString("fileName").substring(pageData.getString("fileName").indexOf(".") + 1);
        //存入业务和库对照表 一对多关系
        PageData pageData1 = new PageData(); 
        pageData1.put("id", UUID.randomUUID().toString());
        //业务表id
        pageData1.put("event_id",map.get("id") );
        pageData1.put("file_id",pageData.get("id"));
        fileMapper.insertFileEvent(pageData1);
        return "success";
    }

    /**
     * 多文件上传
     * @param map
     * @param file
     * @return
     */
    @PostMapping(value = "/insertFiles")
    public String updownloadTwo(@RequestParam Map<String,Object> map, MultipartFile[] file){
        for (int i = 0; i < file.length; i++) {
            PageData pageData=fileFastDfs.uploadFile(file[i],"/group/zyw");
            String type = pageData.getString("fileName").substring(pageData.getString("fileName").indexOf(".") + 1);
            PageData pageData1 = new PageData();
            pageData1.put("id", UUID.randomUUID().toString());
            pageData1.put("event_id",map.get("id") );
            pageData1.put("file_id",pageData.get("id"));
            fileMapper.insertFileEvent(pageData1);
        }
        return "success";
    }

至此上传文件(world等等类型皆可)可以正常存入文件库和业务对照表库和服务器上。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值