Django服务端传输图片到鸿蒙APP

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()),
]
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值