HarmonyOS+Django实现图片上传

话不多说,直接看代码:

HarmonyOS部分代码

TypeScript 复制代码
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})
相关推荐
Mantanmu15 分钟前
Python训练day40
人工智能·python·机器学习
天天爱吃肉821818 分钟前
新能源汽车热管理核心技术解析:冬季续航提升40%的行业方案
android·python·嵌入式硬件·汽车
ss.li21 分钟前
TripGenie:畅游济南旅行规划助手:个人工作纪实(二十二)
javascript·人工智能·python
zhuyasen26 分钟前
深度定制 protoc-gen-go:实现结构体字段命名风格控制
后端·go·protobuf
eternal__day32 分钟前
Spring Cloud 多机部署与负载均衡实战详解
java·spring boot·后端·spring cloud·负载均衡
l木本I34 分钟前
大模型低秩微调技术 LoRA 深度解析与实践
python·深度学习·自然语言处理·lstm·transformer
哆啦A梦的口袋呀38 分钟前
基于Python学习《Head First设计模式》第七章 适配器和外观模式
python·学习·设计模式
十月狐狸41 分钟前
Python字符串进化史:从青涩到成熟的蜕变
python
Livingbody42 分钟前
whisper 命令行解析【2】
后端
何中应43 分钟前
【设计模式-5】设计模式的总结
java·后端·设计模式