package com.doumee.api.web; import com.alibaba.fastjson.JSONObject; import com.doumee.api.BaseController; import com.doumee.biz.system.SystemDictDataBiz; import com.doumee.config.annotation.LoginRequired; import com.doumee.core.annotation.trace.Trace; import com.doumee.core.model.ApiResponse; import com.doumee.core.utils.Constants; import com.doumee.core.utils.DateUtil; import com.doumee.core.utils.FtpUtil; import com.doumee.core.utils.aliyun.ALiYunUtil; import com.doumee.core.utils.tyyun.TyyZosUtil; import com.doumee.dao.business.model.Users; import com.doumee.dao.system.model.SystemDictData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; /** * @author Eva.Caesar Liu * @date 2023/02/14 11:14 */ @Api(tags = "公共接口") @Trace(exclude = true) @RestController @RequestMapping("/public") @Slf4j public class PublicController extends BaseController { @Autowired private SystemDictDataBiz systemDictDataBiz; @LoginRequired @ApiOperation(value = "字典值查询") @GetMapping("/getDictData") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "String", name = "code", value = "大类编码", required = true), @ApiImplicitParam(paramType = "query", dataType = "String", name = "label", value = "子类编码", required = true) }) public ApiResponse getDictData (@RequestParam String code,@RequestParam String label) { SystemDictData systemDictData = systemDictDataBiz.queryByCode(code,label); return ApiResponse.success(systemDictData); } public static FtpUtil ftp = null; @ApiOperation(value = "上传", notes = "上传", httpMethod = "POST", position = 6) @ApiImplicitParams({ @ApiImplicitParam(name = "folder", value = "文件夹", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class), }) @PostMapping(value = "/upload", headers = "content-type=multipart/form-data") public void uploadMobile(String folder, HttpServletRequest request, HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; upload(multipartRequest, response, folder + "/", systemDictDataBiz.queryByCode(Constants.OBJCET_STORAGE,Constants.BUCKETNAME).getCode(), systemDictDataBiz.queryByCode(Constants.OBJCET_STORAGE,Constants.ACCESS_ID).getCode(), systemDictDataBiz.queryByCode(Constants.OBJCET_STORAGE,Constants.ACCESS_KEY).getCode(), systemDictDataBiz.queryByCode(Constants.OBJCET_STORAGE,Constants.RESOURCE_PATH).getCode(), systemDictDataBiz.queryByCode(Constants.OBJCET_STORAGE,Constants.ENDPOINT).getCode()); } @ApiOperation(value = "上传文件到FTP") @RequestMapping(method= RequestMethod.POST,value="api/uploadFtp.do",headers = "content-type=multipart/form-data") @ResponseBody public void uploadFtp(HttpServletRequest request, HttpServletResponse response, String folderCode) throws Exception { System.out.println("上传中"); String folder = systemDictDataBiz.queryByCode(Constants.FTP,folderCode).getCode(); String prefixPath = systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_RESOURCE_PATH).getCode(); InputStream is = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); Map context = new HashMap<>(); try { if(ftp == null){ ftp = new FtpUtil(systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_HOST).getCode(), Integer.parseInt(systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_PORT).getCode()), systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_USERNAME).getCode(), systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_PWD).getCode()); }else{ ftp.connect(); } CommonsMultipartResolver multipartResovler = new CommonsMultipartResolver(); if (multipartResovler.isMultipart(request)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator it = multipartRequest.getFileNames(); while (it.hasNext()) { MultipartFile file = multipartRequest.getFile(it.next()); is = file.getInputStream(); String date = DateUtil.getNowShortDate(); String fName = date+"/"+ UUID.randomUUID()+".jpg"; String fileName = folder+fName; // boolean r = ftp.uploadInputstream(compressImg(is),fileName); boolean r = ftp.uploadInputstream(is,fileName); if(r){ context.put("success", true); context.put("code", 200); context.put("errno",0); JSONObject fileJSON = new JSONObject(); fileJSON.put("halfPath", fName); fileJSON.put("prefixPath", prefixPath); fileJSON.put("folder", folder); fileJSON.put("addr", prefixPath+fileName); context.put("data",fileJSON); context.put("message","请求成功"); writerJson(response, context); return; } } } } catch (Exception e) { log.error("【上传FTP失败】======================"+e.getMessage()); } context.put("code", 0); context.put("message", "上传失败"); context.put("errno",0); writerJson(response, context); return; } public InputStream compressImg(InputStream is){ try { long originalFileSize = is.available(); BufferedImage originalImage = ImageIO.read(is); double compressionRatio = Math.sqrt((double)originalFileSize / (200 * 1024.0)); if(compressionRatio >1){ int compressedWidth = (int) (originalImage.getWidth() / compressionRatio); int compressedHeight = (int) (originalImage.getHeight() / compressionRatio); BufferedImage compressedImage = new BufferedImage(compressedWidth, compressedHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = compressedImage.createGraphics(); graphics.drawImage(originalImage, 0, 0, compressedWidth, compressedHeight, null); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(byteArrayOutputStream); ImageIO.write(compressedImage, "jpg", imOut); InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); graphics.dispose(); return inputStream; }else{ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(byteArrayOutputStream); ImageIO.write(originalImage, "jpg", imOut); InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); return inputStream; } }catch (Exception e){ e.printStackTrace(); } return is; } public void upload(HttpServletRequest request, HttpServletResponse response, String folder, String bucketName, String access_id, String access_key, String resourcePath, String endpoint) throws Exception { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); Map context = new HashMap<>(); CommonsMultipartResolver multipartResovler = new CommonsMultipartResolver(); if (multipartResovler.isMultipart(request)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator it = multipartRequest.getFileNames(); while (it.hasNext()) { MultipartFile file = multipartRequest.getFile((String) it.next());// file // multipartRequest.getFile((String) // it.next()); if (file != null) { // 1、上传到服务器临时文件夹 String uploadFileName = file.getOriginalFilename(); String originname = uploadFileName; if (originname.lastIndexOf("/") >= 0) { originname = originname.substring(originname.lastIndexOf("/") + 1); } String nfix = "";// 后缀名 if (StringUtils.isNotBlank(uploadFileName)) { nfix = uploadFileName.substring(uploadFileName.lastIndexOf(".")); } if (StringUtils.equalsIgnoreCase(nfix, ".exe")) { context.put("code", 4000); context.put("message", "对不起,文件格式\".exe\"上传有误!"); return; } if (StringUtils.equalsIgnoreCase(nfix, ".dll")) { context.put("code", 4000); context.put("message", "对不起,文件格式\".dll\"上传有误!"); return; } if (StringUtils.equalsIgnoreCase(nfix, ".so")) { context.put("code", 4000); context.put("message", "对不起,文件格式\".so\"上传有误!"); return; } String nowDate = DateUtil.getNowShortDate();// 当前时间(年月日) String fileName = UUID.randomUUID().toString() + nfix; String tempFileName = nowDate + "/" + fileName; String key = folder + tempFileName;// 文件名 TyyZosUtil obs = new TyyZosUtil(endpoint,access_id, access_key); if (obs.uploadInputstreamObject(file.getInputStream(),bucketName, key)) { // 移动成功,返回文件名 // sendSuccessMessage(response, resourcePath+key); context.put("success", true); context.put("code", 200); context.put("errno",0); JSONObject fileJSON = new JSONObject(); fileJSON.put("url", resourcePath + key); fileJSON.put("imgaddr", tempFileName); fileJSON.put("imgname", fileName); fileJSON.put("originname", originname); context.put("data",fileJSON); context.put("message","请求成功"); writerJson(response, context); return; } else { // 移动失败 context.put("code", 0); context.put("message", "上传失败"); writerJson(response, context); return; } } } } context.put("code", 0); context.put("message", "上传失败"); context.put("errno",0); writerJson(response, context); return; } public static void writerJson(HttpServletResponse response, Object object) { response.setContentType("application/json"); writer(response, JSONObject.toJSONString(object)); } private static void writer(HttpServletResponse response, String str) { try { StringBuffer result = new StringBuffer(); //设置页面不缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter out = null; out = response.getWriter(); out.print(str); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }