如何上传与世博会的照片?
答
使用世博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,
header: {
'content-type': 'multipart/form-data',
},
});
}
对于一个更全面的例子,包括服务器端的代码,请参阅本回购:https://github.com/exponent/image-upload-example。
答
官方示例使用Node.js的,这里用PHP如何是:
世博
async function takePhotoAndUpload() {
let result = await ImagePicker.launchCameraAsync({
allowsEditing: false, // higher res on iOS
aspect: [4, 3],
});
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop();
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
let formData = new FormData();
formData.append('photo', { uri: localUri, name: filename, type });
return await fetch('http://example.com/upload.php', {
method: 'POST',
body: formData,
header: {
'content-type': 'multipart/form-data',
},
});
}
upload.php的
<?php
move_uploaded_file($_FILES['photo']['tmp_name'], './photos/' . $_FILES['photo']['name']);
?>
如何一次上传多张图片? – Vinay
太棒了,谢谢! – CoredusK
男人,你是救世主。非常感谢! –