HarmonyOS 鸿蒙Next选择相册后上传到服务器
HarmonyOS 鸿蒙Next选择相册后上传到服务器
1、拉起相册,选择图片 沙箱地址:file://media/Photo/2/IMG_1721054311_001/screenshot_20240715_223651.jpg
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
if (photoSelectResult.photoUris.length > 0) {
this.user.profile = photoSelectResult.photoUris[0];
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
2、读取图片为buffer
const file = fs.openSync(photoSelectResult.photoUris[0], fs.OpenMode.READ_WRITE);
this.photoSize = fs.statSync(file.fd).size;
console.info('Photo Size: ’ + this.photoSize);
let buffer = new ArrayBuffer(this.photoSize);
fs.readSync(file.fd, buffer);
fs.closeSync(file);
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
3、写入缓存目录(必须):写入地址:/data/storage/el2/base/haps/entry/cache/abc.jpg
let cacheDir = (getContext(this) as common.UIAbilityContext).cacheDir
let p = cacheDir + ‘/abc.jpg’
<span class="hljs-keyword"><span class="hljs-keyword">try</span></span> {
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> file2 = fs.openSync(p, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> writeLen = fs.writeSync(file2.fd, buffer);
console.info(<span class="hljs-string"><span class="hljs-string">"The length of str is: "</span></span> + writeLen);
} <span class="hljs-keyword"><span class="hljs-keyword">catch</span></span> (err) {
console.error(`Failed to request the upload. err: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(err)}`);
}</code><button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button></pre> <p>4、上传文件 文件地址:internal://cache/abc.jpg</p> <pre style="position: relative;"><code class="language-javascript hljs hljs "> request.uploadFile(getContext(), {
url: <span class="hljs-string"><span class="hljs-string">"http://192.168.1.4:8080/upload"</span></span>,
method:<span class="hljs-string"><span class="hljs-string">"POST"</span></span>,
files:[{filename:<span class="hljs-string"><span class="hljs-string">'abc.jpg'</span></span>,name:<span class="hljs-string"><span class="hljs-string">'files'</span></span>,uri: <span class="hljs-string"><span class="hljs-string">'internal://cache/abc.jpg'</span></span> ,type:<span class="hljs-string"><span class="hljs-string">'jpg'</span></span>}],
header:{
<span class="hljs-string"><span class="hljs-string">'Accept'</span></span>: <span class="hljs-string"><span class="hljs-string">'*/*'</span></span>,
<span class="hljs-string"><span class="hljs-string">'content-type'</span></span>: <span class="hljs-string"><span class="hljs-string">'multipart/form-data'</span></span>
},
data: [],
})</code><button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button></pre> <p>注意事项:上传文件的地址:internal://cache/abc.jpg 经过测试目前好像只支持cache目录,而且还不是绝对地址,所以要把沙箱中的文件复制到cache缓存文件夹才可以上传,刚刚调通,很多地方名称还没参数化,有卡这的可以参考解决了</p></div></div><br><br>关于HarmonyOS 鸿蒙Next选择相册后上传到服务器的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
debug
到此处
const file = fs.openSync(photoSelectResult.photoUris[0], fs.OpenMode.READ_WRITE);
报错
13900001
意思当前用户文件操作不被允许。
这个咋加入权限
不用权限的啊,你是beta几?模拟器还是真机?
期待HarmonyOS能在未来推出更多针对企业用户的解决方案。
beta5 模拟器 不知道为啥一直报这个
try {
//新建一个选择器对象的配置
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
// 文件类型
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
//
PhotoSelectOptions.maxSelectNumber = 5;
// 创建一个对象
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions)
.then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
this.uris = PhotoSelectResult.photoUris
console.info(uris path:${this.uris[0]}
)
// file://media/Photo/2/IMG_1724313834_001/one.jpg
const file = fs.openSync(this.uris[0], fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE);
this.photoSize = fs.statSync(file.fd).size;
console.info('Photo Size: ' + this.photoSize);
let buffer = new ArrayBuffer(this.photoSize);
fs.readSync(file.fd, buffer);
fs.closeSync(file);
let cacheDir = (getContext(this) as common.UIAbilityContext).cacheDir
let p = cacheDir + '/one.jpg'
try {
let file2 = fs.openSync(p, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeLen = fs.writeSync(file2.fd, buffer);
console.info("The length of str is: " + writeLen);
let uploadConfig:request.UploadConfig={
url: '<a class="autoSetLinkTag" href="http://192.168.2.160:8084/common/upload" target="_blank" rel="nofollow">http://192.168.2.160:8084/common/upload</a>',
header: {
'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhNDNmMjFmOTc0NDg0ODBmOGJlYzMzNzY0ODgwNDJhNyIsImV4cCI6MTcyMzcwNzY3M30.USMv9wj7v_SMRwHbRV8hWzDV54_pLg82dc3pXHaFMDk',
'Accept': '*/*'
},
method: 'POST',
files:[{filename:'/one.jpg',name:'files',uri: 'internal://cache/one.jpg' ,type:'jpg'}],
data: [] //额外的数据 json
}
request.uploadFile(context, uploadConfig)
.then((uploadTask: request.UploadTask)=>{
uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
}
});
uploadTask.on('fail', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload fail taskState: ${JSON.stringify(taskStates[i])}`);
}
});
uploadTask.on('progress', (uploadedSize: number, totalSize: number) => {
console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize);
})
})
} catch (err) {
console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
}
}).catch((err: BusinessError) => {
console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
}
问一下,这一段上传的代码,http://192.168.2.160:8084/common/upload 这个有没有简单的例子可以看一下,谢谢
let uploadConfig:request.UploadConfig={ url: 'http://192.168.2.160:8084/common/upload', header: { 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhNDNmMjFmOTc0NDg0ODBmOGJlYzMzNzY0ODgwNDJhNyIsImV4cCI6MTcyMzcwNzY3M30.USMv9wj7v_SMRwHbRV8hWzDV54_pLg82dc3pXHaFMDk', 'Accept': '*/*' }, method: 'POST', files:[{filename:'/one.jpg',name:'files',uri: 'internal://cache/one.jpg' ,type:'jpg'}], data: [] //额外的数据 json } request.uploadFile(context, uploadConfig) .then((uploadTask: request.UploadTask)=>{ uploadTask.on('complete', (taskStates: Array<request.TaskState>) => { for (let i = 0; i < taskStates.length; i++) { console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); } }); uploadTask.on('fail', (taskStates: Array<request.TaskState>) => { for (let i = 0; i < taskStates.length; i++) { console.info(`upload fail taskState: ${JSON.stringify(taskStates[i])}`); } }); uploadTask.on('progress', (uploadedSize: number, totalSize: number) => { console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); }) })