react-native - 如何在拍照后立即将照片传输到 x-www-form-urlencoded EXPO
问题描述
我想拍照,将其保存到相册并立即发送图像。(不要从相册中选择。)
拍摄当前图片,保存在相册中,查看uri是没有问题的。
但是x-www-form-urlencoded发送过程不能正常工作。
我认为发送API的格式可能有问题。
邮递员也附上。(邮递员没有问题。)
takePictureAndCreateAlbum = async () => {
const { uri } = await this.camera.takePictureAsync();
console.log('uri', uri);
const asset = await MediaLibrary.createAssetAsync(uri);
console.log('asset', asset);
const filename = asset.filename;
MediaLibrary.createAlbumAsync('Expo', asset)
// POST API
.then(() => {
var file = new FormData();
file.append({file: uri});
return fetch(/* API_URL */, {
method: 'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded',
'Accept': 'application/json'
} , body : file} )
.then((response) => response.text())
.then((responseData) => {
console.log(responseData);
})
.done();
})
.catch(error => {
Alert.alert('An Error Occurred!')
});
};
解决方案
附加到FormData
实例时,第一个参数是字段名称(您的服务器将作为此文件的对象键获取的内容),第二个参数是以下形式的对象:
{
uri: // The uri you received from the camera,
type: // The file type (i.e.: image/png),
name: // The file name
}
在你的情况下,它会是这样的:
// Split the uri by `.` (periods)
const uriParts = uri.split('.');
// Grab the file type at the end of the uri
const fileType = uriParts[uriParts.length - 1];
file.append('picture', {
uri,
type: `image/${fileType}`,
name: 'FILE-NAME.${fileType}`
});
此外,发送文件时,您的Content-Type
标题应该是multipart/form-data
推荐阅读
- sql - SQL - 组中的 Max() 值不起作用
- javascript - 在特定高度时出现滚动顶部按钮
- javascript - 如果特定产品在购物车中,Woocommerce 将特定产品添加到购物车
- ibm-cloud - AppID userProfileManager.getUserInfo() 给出 UnauthorizedException 错误
- jsonschema - jsonschema 中是否有任何机制可以为数组定义自定义验证器?
- openmp - slurm 使用脚本在单个节点上运行多个 openMP 作业
- php - React + Laravel 7 API - CORS 问题
- python-3.x - 将函数调用调度到对象集合
- google-sheets - 如何计算具有多个条件的唯一值
- .net - Autofac:通过 IComponentRegistration 获取 ServiceLifetime