HarmonyOS+Django实现图片上传

news/2025/2/27 7:18:12

话不多说,直接看代码:

HarmonyOS部分代码

import { router } from "@kit.ArkUI"
import PreferencesUtil from "../utils/PreferencesUtil"
import { photoAccessHelper } from "@kit.MediaLibraryKit"
import fs from '@ohos.file.fs';
import BASE_URL from "../common/Constant";
import { http } from "@kit.NetworkKit";
import { BusinessError, request } from "@kit.BasicServicesKit";
import { JhProgressHUD } from "../utils/LoadingUtil";


// 定义类型
interface UploadResponse {
  body: string
}

interface Response {
  /**
   * 业务状态码
   */
  code: number;

  /**
   * 响应数据
   */
  file_path: string;

  /**
   * 响应消息
   */
  msg: string;
}


@Component
export struct indexContent{
  uiContext?: UIContext
  aboutToAppear() {
    // 初始化Loading
    this.uiContext = this.getUIContext();
    JhProgressHUD.initUIConfig(this.uiContext)
  }

  build() {
    Scroll(){
      Column(){
        Column({space:10}){
          Image($r('app.media.put'))
            .width(45)
            .backgroundColor('#FFFF')
            .borderRadius(10)
            .fillColor('#000')
          Text('上传图片')
            .fontColor('#FFFF')
            .fontSize(18)
          Text('夜间图像增强')
            .fontColor('#ffa29494')
            .fontSize(15)
        }
        .width(300)
        .height(150)
        .border({ width: 3, color: 0xFFFFFF, radius: 10, style: BorderStyle.Dotted })
        .margin({top:20})
        .borderRadius(10)
        .justifyContent(FlexAlign.Center)
        .onClick(async () => {
       
          let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
          PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
          PhotoSelectOptions.maxSelectNumber = 1;

          let photoPicker = new photoAccessHelper.PhotoViewPicker();
          photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
            let select_img_uri = PhotoSelectResult.photoUris[0]
            const context = getContext(this)
            const fileType = 'jpg'
            const fileName = Date.now() + '.' + fileType
            const copyFilePath = context.cacheDir + '/' + fileName

            const file = fs.openSync(select_img_uri, fs.OpenMode.READ_ONLY)
            fs.copyFileSync(file.fd, copyFilePath)
            let files: Array<request.File> = [
              {
                filename: fileName,
                type: fileType,
                name: 'img',
                uri: `internal://cache/${fileName}`
              }
            ]
            request.uploadFile(context, {

              url: `${BASE_URL}/img/progressing/select_img/`, // url 地址

              method: http.RequestMethod.POST, // 请求方法
              header: {
                // 和接口文档的要求的格式对象
                contentType: 'multipart/form-data',

              },
              files, // 文件信息
              data: [] // 额外提交的数据,不能省略
            }).then((res) => {
              res.on('headerReceive', async (value) => {
                const uploadRes = (value as UploadResponse)
                const response = JSON.parse(uploadRes.body) as Response
                let img_uri = `${response.file_path}`  //获取后端返回的url
                if (img_uri){
                  JhProgressHUD.showLoadingText()
                  router.pushUrl({url: "pages/Preview", params:{image_url: img_uri, special: true} })
                }
              })
            })
          }).catch((err: BusinessError) => {
            console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
          });


        })



      }

    }
    .width('100%')
  }
}

Django部分代码

python">class ImgProgressingView(ModelViewSet):

    @action(methods=['POST'], detail=False, url_path='select_img')
    def select_img(self, request):
        """
        选择需要处理的图片
        :param request:
        :return:
        """
        img_file = request.FILES.get('img')

        if not img_file:
            return Response({"code": 400, "msg": "No image file provided"})

        # 确保 media/enhance 目录存在
        enhance_dir = os.path.join('media', 'enhance')
        if not os.path.exists(enhance_dir):
            os.makedirs(enhance_dir)

        # 构建完整的文件路径
        file_path = os.path.join(enhance_dir, img_file.name)

        # 使用 with open 保存图片
        with open(file_path, 'wb') as f:
            for chunk in img_file.chunks():
                f.write(chunk)
        res_file_path = "/" + file_path.replace('\\', '/')
        return Response({"code": 200, "msg": "Image saved successfully", "file_path": res_file_path})


http://www.niftyadmin.cn/n/5869704.html

相关文章

AI如何通过大数据分析提升制造效率和决策智能化

人工智能&#xff08;AI&#xff09;与大数据技术的融合&#xff0c;不仅重新定义了生产流程&#xff0c;更让企业实现了从“经验驱动”到“数据智能驱动”的跨越式升级。 从“模糊经验”到“精准洞察”​​ 传统制造业依赖人工经验制定生产计划&#xff0c;但面对复杂多变的市…

排序算法(3):

这是我们的最后一篇排序算法了&#xff0c;也是我们的初阶数据结构的最后一篇了。 我们来看&#xff0c;我们之前已经讲完了插入排序&#xff0c;选择排序&#xff0c;交换排序&#xff0c;我们还剩下最后一个归并排序&#xff0c;我们今天就讲解归并排序&#xff0c;另外我们还…

C语言基础要素(006):转义字符入门

转义字符入门 转义字符&#xff0c;顾名思议就是转换字符的意义&#xff1b;一个转义字符在书写上是两个或多个字符&#xff0c;但只表示一个含义。‘\n’就是一个转义字符&#xff0c;当printf函数碰到它时&#xff0c;并没有直接输出字符’\‘与’n’&#xff0c;而是将它们…

SQL命令详解之操作数据库

操作数据库 SQL是用于管理和操作关系型数据库的标准语言。数据库操作是SQL的核心功能之一&#xff0c;主要用于创建、修改和删除数据库对象&#xff0c;如数据库、表、视图和索引等。以下是SQL中常见的数据库操作命令及其功能简介&#xff1a; 1. 查询数据库 查询所有的数据库…

X64 TF位和Single-step单步调试的研究

如果在执行指令时&#xff0c;处理器检测到 EFLAGS 寄存器中的 TF 标志被设置&#xff0c;则会生成单步调试异常。该异常属于陷阱类异常&#xff0c;因为异常是在指令执行之后生成的。处理器不会在设置 TF 标志的指令之后立即生成此异常。例如&#xff0c;如果使用 POPF 指令设…

一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用

锋哥原创的Flask3 Python Web开发 Flask3视频教程&#xff1a; 2025版 Flask3 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili 不管是开发网站还是后台管理系统&#xff0c;我们页面里多多少少有公共的模块。比如博客网站&#xff0c;就有公共的头部&…

策略模式环境类的实现方式对比

文章目录 1、策略模式2、聚合策略类实现方式一3、聚合策略类实现方式二4、对比5、补充&#xff1a;ApplicationContextAware接口 1、策略模式 近期工作中&#xff0c;需要处理4.x和5.x两个版本的数据&#xff0c;所以自然想到的是策略模式&#xff0c;写一个抽象类&#xff0c…

DeepSeek-R1的一些影响

DeepSeek-R1火爆全球&#xff0c;肯定不仅仅是开源了一篇论文、一个模型那么简单&#xff0c;更多的是其带来的一些影响&#xff0c;这里简单聊聊。 跳出大模型固有开发范式 NLP&大模型技术发展历程大致如下&#xff1a; 规则方法统计学习方法深度学习方法深度学习预训练…