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("&", "&"); // 下面的是通过解析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); // } }
完毕...