> 文档中心 > (原)SpringBoot+EasyUI生成二维码/条形码+下载图片保存

(原)SpringBoot+EasyUI生成二维码/条形码+下载图片保存


本文为原创​​​​​​​,只为互相学习!

主页:写程序的小王叔叔的博客欢迎来访

支持:点赞收藏关注

社区:JAVA全栈进阶学习社区欢迎加入


生成图片代码:

 配置文件

##生成图片cbs.imagesPathNew=F:/image/##显示/下载图片cbs.imagesPath=file:/f:/image/

配置代码

@Componentpublic class SystemConfigTools {    // 第三方用户唯一凭证,默认是测试号    @Value("${http.imagesPath}")    public String imagesPath; @Value("${http.localImagesPath}")    public String localImagesPath;    /*     * 生成本地图片路径     */    @Value("${cbs.imagesPath}")    public String  cbsImagesPath;    @Value("${local.DownLoadImgPath}")    public String DownLoadImgPath;     /显示/下载图片到本地的路径/    @Value("${cbs.imagesPathNew}")    public String imagesPathNew;    }

生成图片并上传服务器:

@ResponseBody@RequestMapping(value = "/getVerify")public List getVerify(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{    try{ for(int i=1;i<=selectNum;i++){// 生成随机14位数字long randoms = UserNoStr.GenerateRandom(6);BigInteger randomsInt = new BigInteger(randoms + "");SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格String date = df.format(new Date());SimpleDateFormat dfss = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格String dateString = dfss.format(new Date());SimpleDateFormat dfs = new SimpleDateFormat("yyyydMMdd");// 设置日期格String dateNoTime = dfs.format(new Date());Date dateCreate = null;dateCreate = df.parse(date); //本地生成文件夹File file = new File(systemConfig.cbsImagesPath+"//"+dateNoTime+"//imagesQrcode");file.mkdirs();File file1 = new File(systemConfig.cbsImagesPath+"//"+dateNoTime+"//imagesBarcode");file1.mkdirs();//String url="G:\\workspace\\FreeDirectSellingSystem\\projects\\AntiCounterfeiting\\trunk\\free_anti_counterfeiting\\src\\main\\resources\\static";    // 二维码路径(本地图片路径)    String qrcodeImgUrl = systemConfig.imagesPathNew+"\\"+dateNoTime+"\\imagesQrcode/"+dateString    + randomsInt + ".jpg";    // 条形码路径    String barcodeImgUrl =systemConfig.imagesPathNew+"\\"+dateNoTime+"\\imagesBarcode/"+dateString    + randomsInt + ".png"; //本地地址    String localPath = systemConfig.localImagesPath; //服务器地址    String httpPath = systemConfig.imagesPath; //服务区地址    String qrcodeUrl=  localPath +"/"+dateNoTime+"/imagesQrcode/"+dateString    + randomsInt + ".jpg";    // 条形码路径    String barcodeUrl = localPath +"/"+dateNoTime+"/imagesBarcode/"+dateString    + randomsInt + ".png";    // 生成二维码boolean is = QrCodeUtil.createQrCode(qrcodeImgUrl, "to be no1",900, "JPEG");//boolean is = QrCodeUtil.createQrCode("E:/images/", "to be no1",900, "JPEG");// 生成条形码BarcodeUtil.generateFile(randoms + "", barcodeImgUrl); } catch (Exception e) {e.printStackTrace();}}List codePages = 123Service.();return codePages;}

 页面显示代码:

 

 /加载图片*/    function imgFormatter(imgSrc){    var down = $.i18n.prop('i18n_adminManagement_common_headSetting_down');var img  = "
"+down+"
";return img; }

页面展示图片:

@Configurationpublic class WebAppConfig extends WebMvcConfigurerAdapter {  @Value("${cbs.imagesPath}")    private String mImagesPath;    //访问图片方法    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) { if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){     String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();     if(imagesPath.indexOf(".jar")>0){  imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));     }else if(imagesPath.indexOf("classes")>0){  imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));     }     imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/image/";     mImagesPath = imagesPath; } LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath); registry.addResourceHandler("/image/").addResourceLocations(mImagesPath); registry.addResourceHandler("/image/").addResourceLocations("file:/f:/image/");//前台加载图片 super.addResourceHandlers(registry);    }  }

 下载图片:

    /下载防伪码/    function downImg(imgSrc){    var imgUrl = imgSrc.getAttribute("value");    var hash = encode64(imgUrl);  //对数据加密    var codeno = null;    $.ajax({  type : 'get', //传输类型  url : "",   async : false,    data: {imgUrl:imgUrl},   dataType : "json",success:function(data){      codeno = data.codeNo;     $.ajax({  type : 'get',    url : '',    dataType : 'json',   data:{'imgUrl':hash,'codeno':codeno},      success:function(data){      var alertSuccess = $.i18n.prop('i18n_adminManagement_common_headSetting_downSuccess');      var infoMsg = $.i18n.prop('i18n_adminManagement_codeList_btnSetting_infoMsg');      $.messager.show({      title:infoMsg,      msg:alertSuccess,      timeout:500,      width:150,      height:80,      showType:'slide'     });      }      });     }     });     }

 //下载图片@ResponseBody@RequestMapping(value="/downloadPicture", method = RequestMethod.GET)    public Map downloadPicture(HttpServletRequest request,HttpServletResponse response) { Map map = new HashMap();   boolean status = true; String imgUrl = request.getParameter("imgUrl"); String codeno = request.getParameter("codeno"); byte[] imgByte = Base64EncodeChars.decode(imgUrl); String folderName = null;//文件夹名    String fileName = null;//文件名 try {     imgUrl = new String(imgByte);     //构造URL   URL url1 = new URL(imgUrl);   // 打开连接   URLConnection con = url1.openConnection();    SimpleDateFormat sdf  = new SimpleDateFormat("yyyyMMdd");// 设置日期格String dateString = sdf.format(new Date());if ( imgUrl.indexOf("imagesBarcode") != -1 ) {   imgUrl = imgUrl.substring( new String(imgByte).indexOf("imagesBarcode"), imgUrl.length() );}else if ( imgUrl.indexOf("imagesQrcode") !=-1 ){imgUrl = imgUrl.substring( new String(imgByte).indexOf("imagesQrcode"), imgUrl.length() );}folderName = imgUrl.substring( 0 , imgUrl.indexOf("/") );//取文件夹名称fileName = imgUrl.substring(  imgUrl.indexOf("/")+1 );//取文件名称String filePrefix = fileName.substring( 0 ,new String(fileName).indexOf("."));String fileSuffix = fileName.substring( new String(fileName).indexOf(".")+1 );/生成本地图片路径/ folderName = systemConfig.imagesPathNew +"/codeDownImg/"+dateString+"/"+folderName; fileName = folderName+"/"+filePrefix+"_"+codeno+"."+fileSuffix;  System.out.println("------folderName---------\n"+folderName);  System.out.println("------fileName---------\n"+fileName);  File sf=new File(folderName);   if(!sf.exists()){sf.mkdirs();   }    OutputStream os = new FileOutputStream(fileName); // 输入流   InputStream is = con.getInputStream();   // 1K的数据缓冲   byte[] bs = new byte[1024];   // 读取到的数据长度   int len;   // 输出的文件流   // 开始读取   while ((len = is.read(bs)) != -1) {     os.write(bs, 0, len);   }   // 完毕,关闭所有链接   os.close();   is.close();      }  catch(Exception e) {    e.printStackTrace();    }  map.put("status", status); return map;    }

所有文件的代码 - 这是我自己整理的:https://download.csdn.net/download/qq_31653405/11143914