zoukankan      html  css  js  c++  java
  • Java后台生成二维码并上传到阿里云OSS

     依赖

    <!--二维码-->
    		<dependency>
    			<groupId>com.google.zxing</groupId>
    			<artifactId>core</artifactId>
    			<version>3.3.0</version>
    		</dependency>
    		<dependency>
    			<groupId>com.google.zxing</groupId>
    			<artifactId>javase</artifactId>
    			<version>3.3.0</version>
    		</dependency>
    		<!--阿里云oss上传文件-->
    		<dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpclient</artifactId>
    			<version>4.5.1</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpcore</artifactId>
    			<version>4.4.3</version>
    		</dependency>
    		<dependency>
    			<groupId>aliyun-sdk-oss</groupId>
    			<artifactId>aliyun-sdk-oss</artifactId>
    			<version>3.0.0</version>
    		</dependency>
    		<dependency>
    			<groupId>com.aliyun</groupId>
    			<artifactId>aliyun-java-sdk-vod</artifactId>
    			<version>2.11.5</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-mock</artifactId>
    			<version>2.0.8</version>
    		</dependency>
    

     OSSClientUtil(连接阿里云工具类)

    @Slf4j
    @Data
    public class OSSClientUtil {
    
    
    
        private String endpoint = "http://oss-cn-huhehaote.aliyuncs.com";
        // accessKey
        public static String accessKeyId = "阿里云AccessKey ID";
        public static String accessKeySecret = "阿里云Access Key Secret";
        //空间
        private String bucketName = "wokezhineng";
        //文件存储目录
        private String filedir = "image/";
    
        private OSSClient ossClient;
    
        public OSSClientUtil() {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    
        /**
         * 初始化
         */
        public void init() {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    
        /**
         * 销毁
         */
        public void destory() {
            ossClient.shutdown();
        }
    
        /**
         * 上传图片
         *
         * @param url
         */
        public void uploadImg2Oss(String url) throws Exception {
            File fileOnServer = new File(url);
            FileInputStream fin;
            try {
                fin = new FileInputStream(fileOnServer);
                String[] split = url.split("/");
                this.uploadFile2OSS(fin, split[split.length - 1]);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    
    
    //    @RequestMapping("/up")
        public String uploadImg2Oss(MultipartFile file) throws Exception {
            String url="";
            try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String name = UUID.randomUUID() + substring;
                InputStream inputStream = file.getInputStream();
                url=this.uploadFile2OSS(inputStream, name);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                ossClient.shutdown();
            }
            System.out.println(url);
            return url;
        }
    
    
        /**
         * 上传到OSS服务器  如果同名文件会覆盖服务器上的
         *
         * @param instream 文件流
         * @param fileName 文件名称 包括后缀名
         * @return 出错返回"" ,唯一MD5数字签名
         */
        public String uploadFile2OSS(InputStream instream, String fileName) {
            String ret = "";
            try {
    //            //创建上传Object的Metadata
    //            ObjectMetadata objectMetadata = new ObjectMetadata();
    //            objectMetadata.setContentLength(instream.available());
    //            objectMetadata.setCacheControl("no-cache");
    //            objectMetadata.setHeader("Pragma", "no-cache");
    //            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
    //            objectMetadata.setContentDisposition("inline;filename=" + fileName);
                //上传文件
                String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
                filedir=filedir+today+"/"+fileName;
    //           ossClient.putObject(bucketName, filedir, instream, objectMetadata);
    
    
                ossClient.putObject(bucketName, filedir, instream);
                ret="http://wokezhineng.oss-cn-huhehaote.aliyuncs.com/"+filedir;
    
            }finally {
                try {
                    if (instream != null) {
                        instream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ossClient.shutdown();
            }
            return ret;
        }
    
        /**
         * Description: 判断OSS服务文件上传时文件的contentType
         *
         * @param FilenameExtension 文件后缀
         * @return String
         */
        public static String getcontentType(String FilenameExtension) {
            if (FilenameExtension.equalsIgnoreCase(".bmp")) {
                return "image/bmp";
            }
            if (FilenameExtension.equalsIgnoreCase(".gif")) {
                return "image/gif";
            }
            if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                    FilenameExtension.equalsIgnoreCase(".jpg") ||
                    FilenameExtension.equalsIgnoreCase(".png")) {
                return "image/jpeg";
            }
            if (FilenameExtension.equalsIgnoreCase(".html")) {
                return "text/html";
            }
            if (FilenameExtension.equalsIgnoreCase(".txt")) {
                return "text/plain";
            }
            if (FilenameExtension.equalsIgnoreCase(".vsd")) {
                return "application/vnd.visio";
            }
            if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                    FilenameExtension.equalsIgnoreCase(".ppt")) {
                return "application/vnd.ms-powerpoint";
            }
            if (FilenameExtension.equalsIgnoreCase(".docx") ||
                    FilenameExtension.equalsIgnoreCase(".doc")) {
                return "application/msword";
            }
            if (FilenameExtension.equalsIgnoreCase(".xml")) {
                return "text/xml";
            }
    
            return "image/jpeg";
        }
    
        /**
         * 获得url链接
         *
         * @param key
         * @return
         */
        public String getUrl(String key) {
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            // 生成URL
            URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
            if (url != null) {
                return url.toString();
            }
            return null;
        }
    
        /**
         *@Author:yangli
         *@Date:14:47 2018/8/2
         * 删除文件
        **/
        public void deleteFile(String fileName) throws Exception{
            try {
                ossClient.deleteObject(bucketName,fileName);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                ossClient.shutdown();
            }
    
        }
    
        public String getImgUrl(String fileUrl) {
            System.out.println(fileUrl);
            if (!StringUtils.isEmpty(fileUrl)) {
                String[] split = fileUrl.split("/");
                return this.getUrl(this.filedir + split[split.length - 1]);
            }
            return null;
        }
    
    }
    

     二维码生成Util

    @Configuration
    @Slf4j
    public class QRCodeGenerator {
        private final static String CHARSET = "utf-8";
    
        private final static int QRSIZEE = 300;
    
        // 二维码颜色
        private static final int BLACK = 0xFF000000;
        // 二维码颜色
        private static final int WHITE = 0xFFFFFFFF;
        public static BufferedImage createImage(String id){
            String content = id;
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = null;
            try {
                bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRSIZEE, QRSIZEE,hints);
            }catch (Exception e){
                e.printStackTrace();
            }
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }
            return image;
        }
    
    }
    

      

    Controller层

    /**
     * 打印二维码
     * @param
     * @return
     */
    @ApiOperation(value = "打印二维码 ")
    @GetMapping("PrintQRCode")
    public Result PrintQRCode(@ApiParam("点id")@RequestParam(value = "pointId")String pointId, HttpServletResponse response) throws Exception {
    
        return Result.OK(inspectionPointService.PrintQRCode(pointId));
    
    }
    

      

      service层

    public String updateHead(MultipartFile file) throws Exception {
        if (file == null || file.getSize() <= 0) {
            throw new Exception("file不能为空");
        }
        OSSClientUtil ossClient = new OSSClientUtil();
        String name = ossClient.uploadImg2Oss(file);
    
        return name;
    }
    
    public String PrintQRCode(String pointId) throws Exception {
        String[] pointIds=pointId.split(",");
        String urls="";
        for (String id:pointIds) {
            BufferedImage image = QRCodeGenerator.createImage(id);
            // 创建输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                // 将图像输出到输出流中。
                ImageIO.write(image, "jpeg", bos);
                MultipartFile multipartFile = new MockMultipartFile("test.jpeg", "test.jpeg", "", bos.toByteArray());
            if (urls.equals("")){
                urls = updateHead(multipartFile);
            }else{
                urls=urls+","+updateHead(multipartFile);
            }
        }
        return urls;
    }
    

      

     启动项目,访问该接口;返回一个图片地址

     访问

     

     

  • 相关阅读:
    Handler
    闹钟
    自动朗读 TTS
    语音转换成文本
    文件的存与读
    SurfaceView的绘图机制
    Chronometer
    拖动球
    如何整理一个被测对象的特性
    部门间沟通管理心得(持续不定期更新)
  • 原文地址:https://www.cnblogs.com/yangxiaoli/p/13530348.html
Copyright © 2011-2022 走看看