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;
}

  

 啟動項目,訪問該接口;返回一個圖片地址

 

 訪問

 

 

 

 


免責聲明!

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



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