1 Django服务端传输图片到鸿蒙APP
1.1 鸿蒙APP
1.1.1 HML
<div id="wrapper">
<button id="button1" type="capsule" onclick="onClick">获取数据</button>
<image id="image2" src="{{ getImgBase64 }}"></image>
</div>
1.1.2 JS
// @ts-nocheck
import router from '@system.router';
import prompt from '@system.prompt';
import http from '@ohos.net.http';
export default {
data: {
getImgBase64:''
},
//点击按钮函数
onClick(e){
// let声明的变量的作用域是块或者子块
let httpRequest = http.createHttp();
// 创建一个http,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header 事件。
// 每一个HttpRequest对象对应一个Http请求。如需发起多个Http请求,须为每个Http请求创建对应HttpRequest对象。
//返回一个HttpRequest对象,里面包括request、destroy、on和off方法。
let url = "http://xxx.xx.xxx.xxx:8000/hssl_django_app/getDtcImg/";
httpRequest.request(url, {
// 注意请求方法:http.POST
method: 'POST',
}, (err, data)=> { // 判断是否请求成功
if (!err) { // 请求成功
var back_2 = data.result; // 返回值
this.getImgBase64 = "data:image/jpg;base64," + back_2
prompt.showToast({ // 提示请求错误
message: "更新成功",
duration: 5000,
})
} else { // 请求失败
prompt.showToast({ // 提示请求错误
message: 'API请求错误',
duration: 3000,
})
}
})
},
}
1.2 Django
hssl_django_app/views.py
# coding=UTF-8
import base64
import cv2
from django.http import HttpResponse
from rest_framework.views import APIView
class GetDtcImg(APIView):
def post(self, request):
try:
img = cv2.imread('photo.png')
# 此处是核心部分:OPENCV转BASE64
img1 = cv2.imencode('.jpg', img)[1]
back_2 = base64.b64encode(img1)
print(back_2)
return HttpResponse(back_2)
except:
return HttpResponse("图片发送失败")
hssl_django_app/urls.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/2/25 23:25
# @Author : chl
# @File : urls.py
# @Software: PyCharm
from django.conf.urls import url
from hssl_django_app.views import GetDtcImg
app_name = 'hssl_django_app'
urlpatterns = [
url('getDtcImg/', GetDtcImg.as_view()),
]