gpt4 book ai didi

react-native - 如何通过Expo上传照片?

转载 作者:行者123 更新时间:2023-12-03 14:31:06 38 4
gpt4 key购买 nike

我正在使用Expo制作应用程序,并希望让用户拍照或从相机胶卷中选择一张并将其上传到我的服务器。我该怎么做呢?

最佳答案

使用Expo ImagePicker API显示相机或相机胶卷,并获取有关所选图像的信息:

async function takeAndUploadPhotoAsync() {
// Display the camera to the user and wait for them to take a photo or to cancel
// the action
let result = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});

if (result.cancelled) {
return;
}

// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
let filename = localUri.split('/').pop();

// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;

// Upload the image using the fetch and FormData APIs
let formData = new FormData();
// Assume "photo" is the name of the form field the server expects
formData.append('photo', { uri: localUri, name: filename, type });

return await fetch(YOUR_SERVER_URL, {
method: 'POST',
body: formData,
headers: {
'content-type': 'multipart/form-data',
},
});
}

有关包括服务器代码的更全面的示例,请参见此存储库: https://github.com/exponent/image-upload-example

关于react-native - 如何通过Expo上传照片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42521679/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com