当前位置: 首页 > news >正文

HarmonyOS+Django实现图片上传

话不多说,直接看代码:

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部分代码

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

相关文章:

  • AVFormatContext
  • Node.js v16 版本安装
  • 排序(数据结构篇)
  • YOLOv12 ——基于卷积神经网络的快速推理速度与注意力机制带来的增强性能结合
  • 百度觉醒,李彦宏渴望光荣
  • 浅析 Redis 分片集群 Cluster 原理、手动搭建、动态伸缩集群、故障转移
  • 《Spring Boot + MySQL高性能应用实战:性能优化技巧与最佳实践》
  • CMake小结2(PICO为例)
  • 【目标检测旋转框xml2txt】rolabelimg标注的xml格式label转YOLO格式txt文件
  • 【Java项目】基于Spring Boot的旅游管理系统
  • Blueprint —— Events
  • vue3-07模拟vue3的响应式原理Proxy (代理对象)与Reflect (反射对象)
  • NNP_test_cpp
  • 深度强化学习落地调参技巧
  • 企业之IT安全管控概览和实践案例
  • Docker下ARM64架构的源码编译Qt5.15.1,并移植到开发板上
  • 新版本的idea用不习惯,怎么还原为之前版本的UI界面?idea界面还原,idea新版本ui设置
  • 一文了解Java中的虚拟线程新特性
  • linux内核驱动:I2C子系统笔记
  • Android 10.0 Settings中系统菜单去掉备份二级菜单
  • 王毅谈中拉论坛第四届部长级会议重要共识
  • 外交部亚洲司司长刘劲松会见印度驻华大使罗国栋
  • 山西省委常委李金科添新职
  • 飙升至熔断,巴基斯坦股市两大股指收盘涨逾9%
  • 打击网络谣言、共建清朗家园,中国互联网联合辟谣平台2025年4月辟谣榜
  • 上海工匠学院首届学历班56人毕业,新一届拟招生200人