Zimg(10)--Linux環境微服務項目圖片上傳Zimg2.2文件服務器技術說明


使用Spring-cloud技術,從controller-service-serviceImpl

1、controller

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

2、service

/**
     * 圖片文件上傳
     *
     * @param file    請求文件
     * @param request r
     * @return T
     */
    ResponseInfo<UsersinfoDTO> ImgFileUpload(MultipartFile file, HttpServletRequest request);

3、serviceImpl

/**
     * 圖片文件上傳
     *
     * @param file    請求文件
     * @param request r
     * @return T
     */
    @Override
    public ResponseInfo<UsersinfoDTO> ImgFileUpload(MultipartFile file, HttpServletRequest request) {
        try {
            //調取ZimgUploadUtil工具類來上傳圖片
            Map<String, Object> resultMap = ZimgUploadUtil.uploadZimgFile(file, request);
            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;
    }

4、ZimgUploadUtil工具類

package com.sinosoft.zimgUtil;

import com.sinosoft.common.CommonUtil;
import com.sinosoft.config.Constant;
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);


    /**
     * 開始執行圖片上傳
     *
     * @param uploadUrl zimg文件服務器上傳路徑
     * @param fileUrl   本地文件緩存路徑
     * @return 返回response數據
     */
    public static String zimgUpload(String uploadUrl, String fileUrl, File file) {
        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");
            }
            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) {
        String result = "";
        Document doc = null;
        try {
            xml = xml.replace("&", "&amp;");
            // 下面的是通過解析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();
                //String url = "http://10.28.37.56:4869/upload";
                url = url.substring(url.indexOf(":") + 3, url.lastIndexOf(":"));
                result = result.replace("yourhostname", url);
            }
            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) {
        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 = ZimgUploadUtil.readStringXml(
                    ZimgUploadUtil.zimgUpload(Constant.ZIMGUPLOADURL, path, null),
                    Constant.ZIMGUPLOADURL);
            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://10.28.37.56:4869/upload";
//        readStringXml(xmlString, url);
//    }
}

完畢...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM