HarmonyOS 鸿蒙Next system.request 怎么传输formData格式的file对象
HarmonyOS 鸿蒙Next system.request 怎么传输formData格式的file对象
后台接口需要传输multipart/form-data 格式数据,经过PhotoViewPicker后拿到的图片路径,但是后台接口需要file对象。前端代码如下:
const formData = new FormData()
formData.append(‘file’,e.file)
formData.append(‘fileName’, e.fileName)
咨询场景描述:
private openGalleryInternal() {
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select({
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
maxSelectNumber: 1
}, (error, result) => {
if (result) {
this.uploadImage(result.photoUris);
LogUtil.error(this.TAG, ‘’)
result.photoUris.forEach((url) => {
console.log("url: " + url);
})
}
});
}
private uploadImage(paths: string[]) {
const allFiles = Array<request.File>()
for (let i = 0; i <paths.length; i++) {
let path = paths[i]
console.log("path: " + path)
allFiles[i] = {
name: “image” + i + “.jpg”,
filename: “image” + i + “.jpg”,
uri: path,
type: “jpg”
}
}
request.uploadFile(getContext(this), {
url: API_LIST.files,
method: “POST”,
files: allFiles,
header: {
‘content-type’: ‘multipart/from-data;boundary=----WebKitFormBoundaryn8D9asOnAnEU4Js0’,
},
data: [
{
name: “fileName”,
value: ‘ceshi’
},
{
name: “file”,
value: 这里应该传输一个file对象
},
{
name: “appId”,
value: signHead.headData.appId
},
{
name: “uid”,
value: signHead.headData.uid
},
{
name: “token”,
value: signHead.headData.token
},
{
name: “deviceType”,
value: signHead.headData.deviceType
}
]
}, (error, response) => {
if(response) {
response.on(‘progress’, (uploadedSize: number, totalSize: number) => {
console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
})
} else {
console.log("upload failure: " + error)
}
});
}
const formData = new FormData()
formData.append(‘file’,e.file)
formData.append(‘fileName’, e.fileName)
咨询场景描述:
private openGalleryInternal() {
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select({
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
maxSelectNumber: 1
}, (error, result) => {
if (result) {
this.uploadImage(result.photoUris);
LogUtil.error(this.TAG, ‘’)
result.photoUris.forEach((url) => {
console.log("url: " + url);
})
}
});
}
private uploadImage(paths: string[]) {
const allFiles = Array<request.File>()
for (let i = 0; i <paths.length; i++) {
let path = paths[i]
console.log("path: " + path)
allFiles[i] = {
name: “image” + i + “.jpg”,
filename: “image” + i + “.jpg”,
uri: path,
type: “jpg”
}
}
request.uploadFile(getContext(this), {
url: API_LIST.files,
method: “POST”,
files: allFiles,
header: {
‘content-type’: ‘multipart/from-data;boundary=----WebKitFormBoundaryn8D9asOnAnEU4Js0’,
},
data: [
{
name: “fileName”,
value: ‘ceshi’
},
{
name: “file”,
value: 这里应该传输一个file对象
},
{
name: “appId”,
value: signHead.headData.appId
},
{
name: “uid”,
value: signHead.headData.uid
},
{
name: “token”,
value: signHead.headData.token
},
{
name: “deviceType”,
value: signHead.headData.deviceType
}
]
}, (error, response) => {
if(response) {
response.on(‘progress’, (uploadedSize: number, totalSize: number) => {
console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
})
} else {
console.log("upload failure: " + error)
}
});
}
2 回复
通过PhotoViewPicker获取到的图片不能直接用于传输,可以通过将其复制在应用沙箱路径下,然后再用沙箱路径下的文件进行传输。 下面是部分demo:
import { BusinessError } from '[@ohos](/user/ohos).base';
import { rcp } from '[@kit](/user/kit).RemoteCommunicationKit';
import { picker } from '[@kit](/user/kit).CoreFileKit';
import fs from '[@ohos](/user/ohos).file.fs';
import { http } from '[@kit](/user/kit).NetworkKit';
let uploadUrl: string = 'http://192.168.62.4:8080/upload';
function example01(): string {
let uri = '';
let photoViewPicker = new picker.PhotoViewPicker();
let photoSelectOption = new picker.PhotoSelectOptions();
photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoViewPicker.select(photoSelectOption).then((photoSelectResult) => {
console.log("fyh photoSelectResult:" + photoSelectResult);
uri = photoSelectResult.photoUris[0];
console.log("fyh uri:" + uri);
try {
let resultPhoto = fs.openSync(uri, fs.OpenMode.READ_ONLY);
let resultName = resultPhoto.name;
let fileTemp = fs.openSync(getContext().filesDir + resultPhoto.name, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let imageUri = fileTemp.path;
fs.copyFileSync(resultPhoto.fd, fileTemp.fd);
fs.closeSync(resultPhoto);
fs.closeSync(fileTemp);
const httpRequest = http.createHttp();
httpRequest.request(uploadUrl, {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'multipart/form-data',
'Connection': 'keep-alive'
},
expectDataType: http.HttpDataType.ARRAY_BUFFER,
multiFormDataList: [
{
name: 'file',
contentType: 'image/jpg',
filePath: imageUri,
remoteFileName: 'file.jpg'
},
],
}, (err, data) => {
console.log('fyh:上传结束')
httpRequest.destroy();
}
)
} catch (err) {
console.error(fyh:Failed to request the upload. err: ${JSON.stringify(err)});
}
}).catch((err: BusinessError) => {
console.error(Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message});
})
return uri;
}
function testRcpMultiPartUpload() {
example01();
}
function clickget() {
const session = rcp.createSession();
session.get("http://192.168.62.4:8080/getText").then((response) => {
console.log("fyh" + JSON.stringify(response));
}).catch((err: BusinessError) => {
console.error("err:" + JSON.stringify(err));
});
}
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
[@State](/user/State) message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
testRcpMultiPartUpload();
})
Text('getText')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
clickget();
})
}
.width('100%')
}
.height('100%')
}
}
在HarmonyOS鸿蒙系统中,通过system.request
API传输formData
格式的file
对象,通常需要借助HTTP请求库或框架来实现。以下是一个基本的实现思路:
-
构建FormData对象:首先,需要创建一个
FormData
对象,并使用其append
方法将file
对象添加到表单数据中。 -
设置请求头:确保HTTP请求的
Content-Type
头设置为multipart/form-data
,且包含适当的边界字符串(通常框架会自动处理)。 -
发送请求:使用
system.request
或相应的网络请求API发送POST请求,将FormData
对象作为请求体。 -
处理响应:接收并处理服务器的响应。
示例代码(伪代码):
let formData = new FormData();
formData.append('file', fileObject);
let options = {
method: 'POST',
url: 'your-server-url',
headers: {
'Content-Type': 'multipart/form-data' // 通常框架会自动设置正确的边界
},
body: formData
};
system.request(options).then(response => {
// 处理响应
}).catch(error => {
// 处理错误
});
注意:具体实现可能因所使用的框架或库而异。如果system.request
不支持直接传输FormData
对象,可能需要查找相应的替代方案或插件。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html