中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
上传文件的API中支持将应用内部存储路径文件上传,该部分较为简单类似以下代码
request.upload({ url: 上传URL, files:[{ filename: this.videoname, name:'file', uri:'internal://cache/'+this.videoname, type:'mp4', }], data:[{name:"userid",value:this.userid}] }, (err, data) => { if (err) { prompt.showToast({ message: '上传失败' }) console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; } that.uploadvideostatus = 1; prompt.showToast({ message: '上传成功' }) });
主要要说一下如何将图库中文件获取到应用内部存储即internal://cache/ 下
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { console.log("Media resources selected."+value); // Obtain the media selection value. // 使用calculate同步方法,返回OperateData对象。 this.utilInterface = createLocalParticleAbility('应用包名.util.UtilServiceAbility'); this.utilInterface.CopyToCache(value[0],result => { console.info(this.lable+result) that.videoname = result; prompt.showToast({ message: '选择成功' }) that.UploadVideo(); }) }).catch((err) => { console.log("An error occurred when selecting media resources."); prompt.showToast({ message: '选择失败' }) });
在上述代码中调用到PA中的CopyToCache方法
public void CopyToCache(String path, Callback callback) throws IOException { HiLog.info(LABEL_LOG,"开始"); DataAbilityHelper helper=DataAbilityHelper.creator(StaticV.context); HiLog.info(LABEL_LOG,"helper"); String fileName = "EXCEPTION"; //原始文件Uri Uri src = Uri.parse(path); HiLog.info(LABEL_LOG,"parse "+src); //通过DataAbilityHelper获取文件名与文件类型 try { DataAbilityHelper pathHelper = DataAbilityHelper.creator(StaticV.context, src, false); ResultSet resultSet = pathHelper.query(src,null,null); HiLog.info(LABEL_LOG,"数量"+resultSet.getRowCount()); resultSet.goToNextRow(); String srcpath = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DATA)); HiLog.info(LABEL_LOG,"路径"+srcpath); String[] strings = srcpath.split("/"); //文件名 fileName = strings[strings.length-1]; HiLog.info(LABEL_LOG,"文件名"+fileName); resultSet.close(); pathHelper.release(); } catch (DataAbilityRemoteException e) { e.printStackTrace(); } if(!fileName.equals("EXCEPTION")){ FileDescriptor srcfd = null; try { //图库中文件的文件描述符 srcfd = helper.openFile(src,"r"); } catch (DataAbilityRemoteException e) { HiLog.info(LABEL_LOG,"srcfd erro "+e); e.printStackTrace(); } //获取原始文件输入流 FileInputStream srcfis = new FileInputStream(srcfd); HiLog.info(LABEL_LOG,"fis"); String tarpath = StaticV.context.getCacheDir().getAbsolutePath(); HiLog.info(LABEL_LOG,tarpath); //获取应用内部目录的文件输出流 FileOutputStream fos = new FileOutputStream(tarpath+"/"+fileName); int length; byte[] buffer = new byte[1024]; while((length = srcfis.read(buffer))!=-1){ fos.write(buffer,0,length); } HiLog.info(LABEL_LOG,"写入完成"); srcfis.close(); fos.close(); helper.release(); callback.reply(fileName); File tarfile = new File(tarpath+"/"+fileName); HiLog.info(LABEL_LOG, String.valueOf(tarfile.isFile())); } }
StaticV.context即应用上下文
微信扫码分享