package com.yihu.jw.file_upload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.exception.business.file_upload.*;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.IOUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * 文件上传服务
 */
@Service
public class FileUploadService {

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


    @Autowired
    private FastDFSUtil fastDFSHelper;

    @Value("${wlyy.url}")
    private String wlyyUrl;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 文件流上传图片
     * @param inputStream
     * @param originalFileName
     * @return
     * @throws Exception
     */
    public UploadVO uploadImg(InputStream inputStream, String originalFileName,long fileSize,String fastdfs_file_url) throws Exception {
        // 得到文件的完整名称  xxx.txt
        if( null == inputStream){
            throw new FileInputStreamEmptyException("图片文件流不可为空!");
        }

        if(StringUtils.isBlank(originalFileName)){
            throw new FileNameEmptyException("图片文件名不可为空!");
        }

        if(StringUtils.isBlank(fastdfs_file_url)){
            throw new FastfdsFileURLEmptyException("fastdfs url不可为空!");
        }
        //得到文件类型
        String fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"jpg,jpeg,png".contains(fileType)){
            throw new FileWrongFormatException("图片文件格式不正确，请上传jpg,jpeg,png等任一格式!");
        }

        if (!isFileFlag(fileType)){
            throw new FileWrongFormatException("不符合文件上传格式");
        }

        long max = 5*1024*1024;
        if(fileSize > max){
            throw new FileTooLargeSizeException("图片文件过大，请不要超过5M!");
        }

        String fileName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return uploadVO;
    }

     /*
     * 文件流上传附件
     * @param file
     * @return
     * @throws Exception
     */
    public UploadVO uploadAttachment(InputStream inputStream, String originalFileName,long fileSize,String fastdfs_file_url) throws Exception{
        // 得到文件的完整名称  xxx.txt
        if( null == inputStream){
            throw new FileInputStreamEmptyException("附件文件流不可为空!");
        }

        if(StringUtils.isBlank(originalFileName)){
            throw new FileNameEmptyException("图片文件名不可为空!");
        }

        if(StringUtils.isBlank(fastdfs_file_url)){
            throw new FastfdsFileURLEmptyException("fastdfs url不可为空!");
        }

        //得到文件类型
        String fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"doc、docx、pdf、xls、xlsx、jpg、jpeg、png".contains(fileType)){
            throw new FileWrongFormatException("附件文件格式不正确，请上传doc、docx、pdf、xls、xlsx、jpg、jpeg、png等任一格式!");
        }

        long max = 5*1024*1024;
        if(fileSize > max){
            throw new FileTooLargeSizeException("附件文件过大，请不要超过5M!");
        }

        String fileName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return uploadVO;
    }

    /*
     * 文件流上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public UploadVO uploadStream(InputStream inputStream, String originalFileName,String fastdfs_file_url) throws Exception{
        if( null == inputStream){
            throw new FileInputStreamEmptyException("文件内容不可为空!");
        }

        if(StringUtils.isBlank(originalFileName)){
            throw new FileNameEmptyException("文件名不可为空!");
        }

        if(StringUtils.isBlank(fastdfs_file_url)){
            throw new FastfdsFileURLEmptyException("fastdfs url不可为空!");
        }

        //得到文件类型sentitiveLog.txt
        String fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
        String fileName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        if (!isFileFlag(fileType)){
            throw new FileWrongFormatException("不符合文件上传格式");
        }
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return uploadVO;
    }

    public static void main(String[] args) {
        String s ="sentitiveLog.txt";
        System.out.println(s.substring(s.lastIndexOf(".") + 1).toLowerCase());
    }
    /**
     * i健康调用文件传输
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public Map<String, Object> uploadImg(MultipartFile multipartFile) throws Exception {
        Map<String, Object> map = new HashMap<>();
        long size = multipartFile.getSize();
        if(size<=0){
            map.put("uploadStatus",1);//size小于0
            map.put("accessoryUrl",null);//
            return map;
        }
        String fileName = multipartFile.getOriginalFilename();
        String[] fs = fileName.split("\\.");
        String type = fs[1];
        logger.info("uploadImg type："+type);
        //图片常见格式：bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp
       /* List img = new ArrayList(Arrays.asList("bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp"));
        if (!img.contains(type)) {
            map.put("uploadStatus",2);//文件类型不对
            map.put("accessoryUrl",null);//
            return map;
        }*/
       if (!isFileFlag(type)){
           throw new FileWrongFormatException("不符合文件上传格式");
       }

        String response = request(wlyyUrl + "/upload/chat", multipartFile, type);
        org.json.JSONObject rs = new org.json.JSONObject(response);
        Integer status = (Integer) rs.get("status");
        if (status == 200) {
            String url = rs.get("urls") + "";
            map.put("uploadStatus", 0);//文件类型正确
            map.put("accessory", url);//
            return map;
        }
        throw new Exception();
    }
    
    
    /**
     * 调用健康上传语音文件.
     * @param voices_Path
     * @return
     * @throws Exception
     */
    public String uploadWxVoice(String voices_Path) throws Exception {
        String url = "";
        // 文件保存的临时路径
        FastDFSUtil fastDFSUtil = new FastDFSUtil();
        String fileUrls = "";
        File f = new File(voices_Path);
        logger.info("语音文件转换file");
        if (f.exists()) {
            logger.info("语音文件转换file-start");
            FileInputStream input = new FileInputStream(f);
            String fileContenType = "text/plain";
            try {
                logger.info("获取文件类型--开始");
                fileContenType = new MimetypesFileTypeMap().getContentType(f);
                logger.info("获取文件类型--成功--fileContenType："+fileContenType);
            } catch (Exception e) {
                logger.info("获取文件类型--失败："+e.getMessage());
            }
            
            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
            logger.info("语音文件转换file-转换-multipartFile");
            long size = multipartFile.getSize();
            if(size<=0){
//                map.put("uploadStatus",1);//size小于0
//                map.put("accessoryUrl",null);//
                return url;
            }
            String fileName = multipartFile.getOriginalFilename();
            String[] fs = fileName.split("\\.");
            String type = fs[1];
            logger.info("uploadImg type："+type);
            //图片常见格式：bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp
//        List img = new ArrayList(Arrays.asList("bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp"));
//        if (!img.contains(type)) {
//            map.put("uploadStatus",2);//文件类型不对
//            map.put("accessoryUrl",null);//
//            return map;
//        }
            logger.info("语音文件转换file-转换-multipartFile-成功，开始调用i健康接口上传文件");
            String response = request(wlyyUrl + "/upload/chat", multipartFile, type);
            org.json.JSONObject rs = new org.json.JSONObject(response);
            Integer status = (Integer) rs.get("status");
            if (status == 200) {
                url = rs.get("urls") + "";
                logger.info("开始调用i健康接口上传文件成功：url:"+url);
//                map.put("uploadStatus", 0);//文件类型正确
//                map.put("accessory", url);//
                return url;
            }
            throw new Exception();
        }
        return url;
    }


    /**
     * 调用内网本地fasdf
     * @param voices_Path
     * @return
     * @throws Exception
     */
    public String uploadInLocalWxVoice(String voices_Path,String remote_inner_url) throws Exception {
        UploadVO uploadVO = new UploadVO();
        String url = "";
        File f = new File(voices_Path);
        if (f.exists()) {
            logger.info("语音文件转换file-start");
            FileInputStream input = new FileInputStream(f);
            String fileContenType = "text/plain";
            try {
                logger.info("获取文件类型--开始");
                fileContenType = new MimetypesFileTypeMap().getContentType(f);
                logger.info("获取文件类型--成功--fileContenType："+fileContenType);
            } catch (Exception e) {
                logger.info("获取文件类型--失败："+e.getMessage());
            }

            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
            logger.info("语音文件转换file-转换-multipartFile");
            long size = multipartFile.getSize();
            if(size<=0){
                return url;
            }
            String fileName = multipartFile.getOriginalFilename();
            String[] fs = fileName.split("\\.");
            String type = fs[1];
            logger.info("语音文件转换file-转换-multipartFile-成功，开始调用内网接口上传文件");
            String rs = request(remote_inner_url, multipartFile, type);
            logger.info(rs);
            JSONObject json = JSON.parseObject(rs);
            uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
            if (uploadVO !=null) {
                url = uploadVO.getFullUri();
                logger.info("开始调用内网接口上传文件成功：url:"+url);
//                map.put("uploadStatus", 0);//文件类型正确
//                map.put("accessory", url);//
                return url;
            }
        }
        return url;
    }

    /**
     * 调用内网上传图片.
     * @param files
     * @return
     * @throws Exception
     */
    public String uploadInLocalWxImage(String files,String tempPath,String remote_inner_url) throws Exception {
        UploadVO uploadVO = new UploadVO();
        System.out.println("files====="+files);
        System.out.println("tempPath====="+tempPath);
        // 文件保存的临时路径
        String[] fileArray = files.split(",");
        String fileUrls = "";
        for (String file : fileArray) {
            System.out.println("file+++"+file);
            File f = new File(tempPath + "/"+file);
            File fs = new File(tempPath +"/"+ file + "_small");
            if (f.exists()) {
                logger.info("图片文件转换file-start");
                FileInputStream input = new FileInputStream(f);
                String fileContenType = "text/plain";
                try {
                    logger.info("获取文件类型--开始");
                    fileContenType = new MimetypesFileTypeMap().getContentType(f);
                    logger.info("获取文件类型--成功--fileContenType："+fileContenType);
                } catch (Exception e) {
                    logger.info("获取文件类型--失败："+e.getMessage());
                }

                MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
                logger.info("图片文件转换file-转换-multipartFile");
                long size = multipartFile.getSize();
                if(size<=0){

                    return fileUrls;
                }

                logger.info("图片文件转换file-转换-multipartFile-成功，开始调用内网接口上传文件");
                String rs = request(remote_inner_url, multipartFile, fileContenType);
                logger.info(rs);
                JSONObject json = JSON.parseObject(rs);
                uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
                if (uploadVO != null) {
                    fileUrls += uploadVO.getFullUri();
                    f.delete();
                    if (fs.exists()) {
                        fs.delete();
                    }
                }
            }
        }

        return fileUrls;
    }

    /**
     * 调用内网上传语音文件.
     * @param voices_Path
     * @return
     * @throws Exception
     */
    public String uploadWxVoiceToEntrance(String remoteUrl,String voices_Path) throws Exception {
        String url = "";
        // 文件保存的临时路径
        FastDFSUtil fastDFSUtil = new FastDFSUtil();
        String fileUrls = "";
        File f = new File(voices_Path);
        logger.info("语音文件转换file");
        if (f.exists()) {
            logger.info("语音文件转换file-start");
            FileInputStream input = new FileInputStream(f);
            String fileContenType = "text/plain";
            try {
                logger.info("获取文件类型--开始");
                fileContenType = new MimetypesFileTypeMap().getContentType(f);
                logger.info("获取文件类型--成功--fileContenType："+fileContenType);
            } catch (Exception e) {
                logger.info("获取文件类型--失败："+e.getMessage());
            }

            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
            logger.info("语音文件转换file-转换-multipartFile");
            long size = multipartFile.getSize();
            if(size<=0){
//                map.put("uploadStatus",1);//size小于0
//                map.put("accessoryUrl",null);//
                return url;
            }
            String fileName = multipartFile.getOriginalFilename();
            String[] fs = fileName.split("\\.");
            String type = fs[1];
            logger.info("uploadImg type："+type);
            //图片常见格式：bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp
//        List img = new ArrayList(Arrays.asList("bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp"));
//        if (!img.contains(type)) {
//            map.put("uploadStatus",2);//文件类型不对
//            map.put("accessoryUrl",null);//
//            return map;
//        }
            logger.info("语音文件转换file-转换-multipartFile-成功，开始调用i健康接口上传文件");
            String response = request( remoteUrl, multipartFile, type);
            JSONObject json = JSON.parseObject(response);
            Integer status = json.getInteger("status");
            if (status == 200) {
                UploadVO uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
                return uploadVO.getFullUri();
            }
            throw new Exception();
        }
        return url;
    }
    
    /**
     * 调用健康上传图片.
     * @param image_Path
     * @return
     * @throws Exception
     */
    public String uploadWxImage(String image_Path) throws Exception {
        String url = "";
        // 文件保存的临时路径
        FastDFSUtil fastDFSUtil = new FastDFSUtil();
        String fileUrls = "";
        File f = new File(image_Path);
        logger.info("图片文件转换file");
        if (f.exists()) {
            logger.info("图片文件转换file-start");
            FileInputStream input = new FileInputStream(f);
            String fileContenType = "text/plain";
            try {
                logger.info("获取文件类型--开始");
                fileContenType = new MimetypesFileTypeMap().getContentType(f);
                logger.info("获取文件类型--成功--fileContenType："+fileContenType);
            } catch (Exception e) {
                logger.info("获取文件类型--失败："+e.getMessage());
            }
            
            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
            logger.info("图片文件转换file-转换-multipartFile");
            long size = multipartFile.getSize();
            if(size<=0){
//                map.put("uploadStatus",1);//size小于0
//                map.put("accessoryUrl",null);//
                return url;
            }
            String fileName = multipartFile.getOriginalFilename();
            String[] fs = fileName.split("\\.");
            String type = fs[1];
            logger.info("uploadImg type："+type);
            //图片常见格式：bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp
//        List img = new ArrayList(Arrays.asList("bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp"));
//        if (!img.contains(type)) {
//            map.put("uploadStatus",2);//文件类型不对
//            map.put("accessoryUrl",null);//
//            return map;
//        }
            logger.info("图片文件转换file-转换-multipartFile-成功，开始调用i健康接口上传文件");
            String response = request(wlyyUrl + "/upload/chat", multipartFile, type);
            org.json.JSONObject rs = new org.json.JSONObject(response);
            Integer status = (Integer) rs.get("status");
            if (status == 200) {
                url = rs.get("urls") + "";
                logger.info("开始调用i健康接口上传文件成功：url:"+url);
//                map.put("uploadStatus", 0);//文件类型正确
//                map.put("accessory", url);//
                return url;
            }
            throw new Exception();
        }
        return url;
    }

    public String request(String remote_url, MultipartFile file, String type) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交，对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(type)) {
                builder.addTextBody("type", type); //发送类型
            }
            logger.info("type===="+type);
            if (!isFileFlag(type)){
                throw new FileWrongFormatException("不符合文件上传格式");
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /*
     * base64上传图片
     * @param jsonData,头像转化后的输入流
     * @return
     * @throws Exception
     */
    public UploadVO uploadImages(String jsonData,String fastdfs_file_url) throws Exception {

        if(StringUtils.isBlank(jsonData)){
            throw new FileInputStreamEmptyException("图片的base64文件文件流不可为空!");
        }

        if(StringUtils.isBlank(fastdfs_file_url)){
            throw new FastfdsFileURLEmptyException("fastdfs url不可为空!");
        }
        String date = URLDecoder.decode(jsonData,"UTF-8");
        String[] fileStreams = date.split(",");
        String is = URLDecoder.decode(fileStreams[1],"UTF-8").replace(" ","+");
        byte[] in = Base64.getDecoder().decode(is);

        String pictureName = fileStreams[0].substring(0,fileStreams[0].length()-1);
        String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
        String description = null;
        if ((pictureName != null) && (pictureName.length() > 0)) {
            int dot = pictureName.lastIndexOf('.');
            if ((dot > -1) && (dot < (pictureName.length()))) {
                description = pictureName.substring(0, dot);
            }
        }
        InputStream inputStream = new ByteArrayInputStream(in);
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, "png", "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(remoteFileName);
        uploadVO.setFileType(groupName);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        //返回文件路径
        return uploadVO;
    }


    /***
     *
     * 将图片转换为Base64<br>
     * 将base64编码字符串解码成img图片
     * @param imgFile
     * @return
     */
    public static String getImgStr(String imgFile){
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgFile);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容放到内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.getEncoder().encodeToString(data.toByteArray());
    }


    public InputStream getInputStream(String downloadFilePath) throws Exception{
        InputStream inputStream = null;

        //从文件链接里获取文件流
        URL url = new URL(downloadFilePath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(180 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        inputStream = conn.getInputStream();
        return inputStream;
    }
    public void deleteFile(String groupName,String fileName) throws  Exception{
        fastDFSHelper.delete(groupName,fileName);
    }


    /*
     * base64上传图片心脏
     * @param jsonData,头像转化后的输入流
     * @return
     * @throws Exception
     */
    public UploadVO uploadImagesBase64(String jsonData,String fastdfs_file_url) throws Exception {

        if(StringUtils.isBlank(jsonData)){
            throw new FileInputStreamEmptyException("图片的base64文件文件流不可为空!");
        }

        if(StringUtils.isBlank(fastdfs_file_url)){
            throw new FastfdsFileURLEmptyException("fastdfs url不可为空!");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bfile = decoder.decodeBuffer(jsonData);

        InputStream inputStream = new ByteArrayInputStream(bfile);
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, "png", "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(remoteFileName);
        uploadVO.setFileType(groupName);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        //返回文件路径
        return uploadVO;
    }


    public boolean isFileFlag(String type){
        List img = new ArrayList(Arrays.asList("bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp","xls","xlsx","text/plain"));
        if (!img.contains(type)) {
            return false;
        }
        return true;
    }
}

