如何通过Expo上传照片? [英] How can I upload a photo with Expo?
本文介绍了如何通过Expo上传照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Expo制作一个应用程序,并希望让用户拍照或从他们的相机胶卷中挑选一张照片并将其上传到我的服务器上.我该怎么做?
I'm making an app with Expo and want to let the user take a photo or pick one from their camera roll and upload it to my server. How do I do this?
推荐答案
使用Expo ImagePicker
API显示相机或相机胶卷并获取有关所选图像的信息:
Use the Expo ImagePicker
API to display either the camera or the camera roll and get back information about the selected image:
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 .
For a more comprehensive example including the server code, see this repo: https://github.com/exponent/image-upload-example.
这篇关于如何通过Expo上传照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文