需要安装 crypto-js axios
iflytek.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { HmacSHA256, enc } from 'crypto-js';
@Injectable() export class IflytekService { private OCR_SECRET = '自己的Secret' private OCR_KEY = '自己的key' private OCR_APPID = '自己的appid'
async ocr(file: Express.Multer.File) { const date = new Date().toUTCString() const host = 'api.xf-yun.com' const signature_origin = "host: api.xf-yun.com\n" + "date: " + date + "\nPOST /v1/private/sf8e6aca1 HTTP/1.1" const signature = enc.Base64.stringify(HmacSHA256(signature_origin, this.OCR_SECRET)) const authorization_origin = `api_key="${this.OCR_KEY}",algorithm="hmac-sha256",headers="host date request-line",signature="${signature}"` const authorization = enc.Base64.stringify(enc.Utf8.parse(authorization_origin));
const fileStr = file.originalname.split('.') const filetype = fileStr[fileStr.length - 1]
const imageData = file.buffer.toString("base64")
const { data,statusText } = await axios({ method: 'post', url: `https://api.xf-yun.com/v1/private/sf8e6aca1?authorization=${authorization}&host=${host}&date=${date}`, data: { header: { app_id: this.OCR_APPID, status: 3 }, parameter: { sf8e6aca1: { category: "ch_en_public_cloud", result: { encoding: "utf8", compress: "raw", format: "json" } } }, payload: { sf8e6aca1_data_1: { encoding: filetype, status: 3, image: imageData } } } }) if(data?.payload?.result?.text) { const words = enc.Base64.parse(data?.payload?.result?.text) const str = enc.Utf8.stringify(words) return { success: true, data: JSON.parse(str) } } else { return { success: false } } } }
|