SpringCloud(6)—— 国寿i动项目经验之(Zimg(2.2、3.1)图片服务器上传技术)

Zimg(2.2、3.1)图片服务器上传技术 

  Linux服务器需要安装zimg图片服务器,目前我们用到的有 2.2版本、3.1版本,有人可能感到比较迷惑,因为之前最开始用的是2.2版本,但是后来发现2.2版本并不是很稳定,当访问路径错误的时候会导致2.2图片发服务器莫名挂掉。后来考虑建立3.1版本zimg图片服务器,因为之前2.2版本产生的历史图片没有办法进行迁移,现在最新上传的走3.1版本,读取图片的就出现了两套图片服务器2.2版本(历史图片)、3.1版本(最新图片),这就是我们现在项目用到2.2版本、3.1版本的原因。

  2.2版本上传图片服务器功能代码,如下:

package com.sinosoft.zimgUtil;

import com.sinosoft.common.CommonUtil;
import com.sinosoft.common.Constant;
import com.sinosoft.constant.ConfigProperties;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by xushuyi on 2017/3/10.
 */
public class ZimgUploadUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZimgUploadUtil.class);

    public static String zimgUpload(String uploadUrl, String fileUrl,File file){
        return zimgUpload(uploadUrl,fileUrl,file,null);
    }
    /**
     * 开始执行图片上传
     *
     * @param uploadUrl zimg文件服务器上传路径
     * @param fileUrl   本地文件缓存路径
     * @return 返回response数据
     */
    public static String zimgUpload(String uploadUrl, String fileUrl, File file,ConfigProperties configProperties) {
        HttpURLConnection conn = null;
        DataInputStream in = null;
        OutputStream out = null;
        BufferedReader reader = null;
        boolean uploadFlag = false;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "--9999--";
        try {
            //打开和url之间的连接
            conn = (HttpURLConnection) (new URL(uploadUrl)).openConnection();
            //设置连接请求的超时时间
            conn.setConnectTimeout(5000);
            //设置读取的超时时间
            conn.setReadTimeout(30000);
            //发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //设置post请求
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            out = new DataOutputStream(conn.getOutputStream());

            //根据本地文件路径处理文件上传逻辑
            if (!CommonUtil.isEmpty(fileUrl)) {
                File cfile = new File(fileUrl);
                String inputName = "uploadFile";
                String contentType = fileContentType(cfile);
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY)
                        .append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\""
                        + inputName + "\"; filename=\"" + cfile.getName()
                        + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
                in = new DataInputStream(
                        new FileInputStream(cfile));
                uploadFlag = true;
            }
            //处理现成文件处理文件上传逻辑
            if (file != null) {
                if (!uploadFlag) {
                    String inputName = "uploadFile";
                    String contentType = fileContentType(file);
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"; filename=\"" + file.getName()
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    in = new DataInputStream(
                            new FileInputStream(file));
                }
            }
            byte[] bufferOut = new byte[1024];
            int bytes = -1;
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            // 读取返回数据
            StringBuffer resBuf = new StringBuffer();
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                resBuf.append(line).append("\n");
            }
            LOGGER.info("接收到ZIMG文件服务器返回结果:" + resBuf.toString());
            return (resBuf.toString());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("发送post请求" + uploadUrl + "出错,原因:" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                    reader = null;
                }
                if (out != null) {
                    out.close();
                    out = null;
                }
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("释放资源出错");
            }
        }
        return null;
    }

    /**
     * 获取文件类型
     *
     * @param file 文件
     * @return 文件类型
     */
    private static String fileContentType(File file) {
        try {
            String filename = file.getName();
            //根据文件获取文件类型
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            //contentType非空采用filename匹配默认的图片类型
            if (!"".equals(contentType)) {
                if (filename.endsWith(".png")) {
                    contentType = "image/png";
                } else if (filename.endsWith(".jpg")
                        || filename.endsWith(".jpeg")
                        || filename.endsWith(".jpe")) {
                    contentType = "image/jpeg";
                } else if (filename.endsWith(".gif")) {
                    contentType = "image/gif";
                } else if (filename.endsWith(".ico")) {
                    contentType = "image/image/x-icon";
                }
            }
            if (CommonUtil.isEmpty(contentType)) {
                contentType = "application/octet-stream";
            }
            return contentType;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获取文件类型错误" + e.getMessage());
            return null;
        }
    }

    /**
     * 解析xml字符串
     *
     * @param xml 字符串
     */
    public static String readStringXml(String xml, String url,ConfigProperties configProperties) {
        String result = "";
        Document doc = null;
        try {
            xml = xml.replace("&", "&");
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
            Iterator iterator = rootElt.elementIterator("head"); // 获取根节点下的子节点head
            // 遍历head节点
            while (iterator.hasNext()) {
                Element recordEle = (Element) iterator.next();
                String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值
                System.out.println("title:" + title);
            }
            Iterator iterator1 = rootElt.elementIterator("body"); ///获取根节点下的子节点body
            // 遍历body节点
            while (iterator1.hasNext()) {
                Element recordEless = (Element) iterator1.next();
                String md5 = recordEless.elementTextTrim("h1"); // 拿到body节点下的子节点h1加密值
                System.out.println("Md5:" + md5.substring(md5.indexOf(":") + 1).trim());
                String resData = String.valueOf(recordEless.getData());
                result = resData.substring(resData.indexOf(":") + 1).trim();
                if(configProperties==null){
                    result = result.replace(Constant.ZIMGUPLOAD, Constant.ZIMGUPLOADURL_PROXY);
                }else{
                    result = result.replace(configProperties.getZimgupload(), configProperties.getZimguploadurl_proxy());
                }
                result = result.substring(0, result.indexOf("?"));//将路径后面拼接的参数都给去掉
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("xml字符串解析错误,xml:" + xml);
            LOGGER.error("出错原因:" + e.getMessage());
        }
        return null;
    }

    /**
     * 将图片转为字节编码数据
     *
     * @param file_path 文件路径
     * @return 字节数组
     */
    public static byte[] imageBinary(String file_path) {
        File f = new File(file_path);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(bi, fileContentType(f), bos);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传图片
     *
     * @param file    图片文件
     * @param request req
     * @return map
     */
    public static Map<String, Object> uploadZimgFile(MultipartFile file, HttpServletRequest request,ConfigProperties configProperties) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (file.isEmpty()) {
                LOGGER.error("上传文件为空!");
                resMap.put("Flag", "N#上传文件为空!");
                return resMap;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            LOGGER.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            LOGGER.info("上传的后缀名为:" + suffixName);
            // 项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            // 自定义的文件名称
            String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
            String path = realPath + trueFileName;
            LOGGER.info("存放图片文件的路径:" + path);
            File localFile = new File(path);
            file.transferTo(localFile);
            //开始执行zimg文件服务器图片上传

            String result ="";
            if(configProperties==null){
                LOGGER.info("上传图片路径--:" + Constant.ZIMGUPLOADURL);
                result = ZimgUploadUtil.readStringXml(
                        ZimgUploadUtil.zimgUpload(Constant.ZIMGUPLOADURL, path, null,null),
                        Constant.ZIMGUPLOADURL,null);
            }else{
                LOGGER.info("上传图片路径--:" + configProperties.getZimgupload());
                result = ZimgUploadUtil.readStringXml(
                        ZimgUploadUtil.zimgUpload(configProperties.getZimguploadurl(), path, null,configProperties),
                        configProperties.getZimguploadurl(),configProperties);
            }

            LOGGER.info("上传图片结束,结果Result:" + result);
            resMap.put("Flag", "Y");
            resMap.put("result", result);
            //删除本地缓存文件
            localFile.delete();
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("上传图片异常,原因:" + e.getMessage());
            resMap.put("Flag", "N#上传图片异常,原因:" + e.getMessage());
            return resMap;
        }
    }

//    public static void main(String[] args) {
//        // 下面是需要解析的xml字符串例子
//        String xmlString = "<html>"
//                + "<head>"
//                + "<title>Upload Successfully</title>"
//                + "</head>"
//                + "<body>"
//                + "<h1>MD5: 9e9cc6b792bed194a276b993050f0688</h1>"
//                + "Image upload successfully! You can get this image via this address:<br/><br/>"
//                + "http://yourhostname:4869/9e9cc6b792bed194a276b993050f0688?w=width&h=height&g=isgray"
//                + "</body>"
//                + "</html>";
////        String url = "http://218.107.129.234:10050/upload";
//        String url = "http://10.28.37.56:4869/upload";
//        System.out.println(readStringXml(xmlString, url));
//    }
}

3.1版本上传图片服务器功能代码,如下:

package com.sinosoft.zimgUtil;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.common.CommonUtil;
import com.sinosoft.constant.ConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xushuyi on 2017/3/10.
 */
public class Zimg3UploadUtil {

    /**
     * 日志打印
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Zimg3UploadUtil.class);

    /**
     * 上传图片
     *
     * @param file    图片文件
     * @param request req
     * @return map
     */
    public static Map<String, Object> uploadZimg3File(MultipartFile file, HttpServletRequest request, ConfigProperties configProperties) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (file.isEmpty()) {
                LOGGER.error("上传文件为空!");
                resMap.put("Flag", "N#上传文件为空!");
                return resMap;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            LOGGER.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            LOGGER.info("上传的后缀名为:" + suffixName);
            // 项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            // 自定义的文件名称
            String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
            String path = realPath + trueFileName;
            LOGGER.info("存放图片文件的路径:" + path);
            File localFile = new File(path);
            file.transferTo(localFile);
            //开始执行zimg文件服务器图片上传
            LOGGER.info("上传图片路径--:" + configProperties.getZimguploadurl());
            String result = Zimg3UploadUtil.readStringJson(Zimg3UploadUtil.sendZimgPost(configProperties.getZimguploadurl(),
                    fileToBinary(localFile, suffixName), suffixName), configProperties.getZimguploadurl_proxy());
            LOGGER.info("上传图片结束,结果Result:" + result);
            resMap.put("Flag", "Y");
            resMap.put("result", result);
            //删除本地缓存文件
            localFile.delete();
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("上传图片异常,原因:" + e.getMessage());
            resMap.put("Flag", "N#上传图片异常,原因:" + e.getMessage());
            return resMap;
        }
    }

    /**
     * 处理上传图片返回结果
     * {"ret":true,"info":{"md5":"16a6fe01f87edc35b0f680f7d159bcf8","size":86627}}
     *
     * @param json json字符串
     * @return str
     */
    private static String readStringJson(String json, String url_proxy) {
        try {
            Map<String, Object> jsonurl = JSONObject.parseObject(json);
            Map info = (Map) jsonurl.get("info");
            return (url_proxy.concat(String.valueOf(info.get("md5"))));
        } catch (Exception e) {
            LOGGER.error("处理上传图片返回结果失败,原因:" + CommonUtil.getExceptionStackTrace(e));
            return null;
        }
    }

    /**
     * zimg文件服务器上传
     *
     * @param url      上传路径
     * @param PostData 请求数据
     * @param fileType 文件类型
     * @return backstr
     */
    private static String sendZimgPost(String url, byte[] PostData, String fileType) {
        OutputStream outStream = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", fileType);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //二进制
            outStream = conn.getOutputStream();
            outStream.write(PostData);
            outStream.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Java文件操作 获取文件扩展名
     *
     * @param filename 文件名
     * @return str
     */
    private static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 将文件转为字节数组
     *
     * @param file     文件
     * @param fileType 文件类型
     * @return byte
     */
    private static byte[] fileToBinary(File file, String fileType) {
        BufferedImage bi;
        try {
            bi = ImageIO.read(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(bi, fileType, bos);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

单个图片上传调取工具类逻辑:

/**
* 图片文件上传
*
* @param file 请求文件
* @param request r
* @return T
*/
@ApiOperation("图片文件上传")
@PostMapping(value = "/ImgFileUpload/")
public ResponseInfo<UsersinfoDTO> ImgFileUpload(@RequestBody MultipartFile file, HttpServletRequest request) {
LOGGER.info("图片文件上传...");
return (usersinfoService.ImgFileUpload(file, request));
}



/**
* 图片文件上传
*
* @param file 请求文件
* @param request r
* @return T
*/
@Override
public ResponseInfo<UsersinfoDTO> ImgFileUpload(MultipartFile file, HttpServletRequest request) {
try {
//调取ZimgUploadUtil工具类来上传图片 2.2版本
// Map<String, Object> resultMap = ZimgUploadUtil.uploadZimgFile(file, request, configProperties);
//调取ZimgUploadUtil工具类来上传图片 3.1版本
Map<String, Object> resultMap = Zimg3UploadUtil.uploadZimg3File(file, request, configProperties);
String flag = (String) resultMap.get("Flag");
if (!flag.equals("Y")) {
return (new ResponseInfo<>(false, flag.substring(2), 400));
}
String result = (String) resultMap.get("result");
if (!CommonUtil.isEmpty(result)) {
LOGGER.info("图片文件上传ZIMG文件服务器路径:" + result);
Map<String, Object> resMap = new HashMap<String, Object>();
resMap.put("ImgUploadUrl", result);
return (new ResponseInfo(true, "success", resMap));
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("图片文件上传失败,原因:" + e.getMessage());
return (new ResponseInfo<>(false, "图片文件上传失败,原因:" + e.getMessage(), 400));
}
return null;
}

批量图片上传调取工具类逻辑:

/**
     * 图片文件上传
     *
     * @param files    请求文件
     * @param request r
     * @return T
     */
    @ApiOperation("批量图片文件上传")
    @PostMapping(value = "/ImgsFileUpload/")
    public ResponseInfo<UsersinfoDTO> ImgsFileUpload( HttpServletRequest request,
                                                      @RequestBody MultipartFile[] files
                                                      ) {
        LOGGER.info("图片文件上传...");
        return (usersinfoService.ImgsFileUpload(files, request));
    }

/**
* 批量图片文件上传
*
* @param request r
* @return T
*/
@Override
public ResponseInfo<UsersinfoDTO> ImgsFileUpload(MultipartFile[] file1, HttpServletRequest request) {
Map resultmap = new HashMap();
if (file1 != null) {
for (int i = 0; i < file1.length; i++) {
MultipartFile file = file1[i];
ResponseInfo r = ImgFileUpload(file, request);
if (r.getEntityies() != null && r.getEntityies().size() > 0) {
Map map = (Map) r.getEntityies().get(0);
resultmap.put(i + 1, map.get("ImgUploadUrl"));
}
}
}
return (new ResponseInfo(true, "success", resultmap));
}
posted @ 2017-06-10 18:40  xu_shuyi  阅读(514)  评论(0)    收藏  举报