欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > HarmonyOS+Django实现图片上传

HarmonyOS+Django实现图片上传

2025/2/28 6:07:09 来源:https://blog.csdn.net/m0_71660867/article/details/145878860  浏览:    关键词: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?: UIContextaboutToAppear() {// 初始化Loadingthis.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() + '.' + fileTypeconst copyFilePath = context.cacheDir + '/' + fileNameconst 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 Responselet img_uri = `${response.file_path}`  //获取后端返回的urlif (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})

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词