?app.json:
https://docs.expo.dev/versions/latest/sdk/imagepicker/文章來源地址http://www.zghlxwxcb.cn/news/detail-615781.html
{
"expo": {
"plugins": [
[
"expo-image-picker",
{
"photosPermission": "The app accesses your photos to let you share them with your friends."
}
]
]
}
}
?我的RN代碼:
import * as ImagePicker from 'expo-image-picker'
const handleUploadAvatar = async () => {
try {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
base64: true,
//allowsEditing: true,
//aspect: [4, 3],
//quality: 1,
})
if (!result.canceled) {
const formData = new FormData()
let uri = result.assets[0].uri
let uriArr = uri.split('/')
let name = uriArr[uriArr.length - 1]
console.log(uri)
setAvatar(uri)
formData.append('file', {
uri,
name,
//type: result.assets[0].type,
type: 'image/jpeg',
})
Api.h5.uploadFile(formData).then((res) => {
console.log(res)
if (res.code === 200) {
console.log('成功')
}
})
} else {
console.log('取消文件選擇')
}
} catch (error) {
console.log('選擇文件時出錯', error)
}
}
<View style={style.mRegisterRow}>
<View style={style.mRegisterAvavtarTextWrap}>
<Text style={style.mRegisterAvavtarText}>頭像</Text>
</View>
{avatar ? (
<TouchableWithoutFeedback onPress={handleUploadAvatar}>
<Image
source={{ uri: avatar }}
style={style.mRegisterAvatar}
></Image>
</TouchableWithoutFeedback>
) : (
<View style={style.mRegisterUploadIcoWrap}>
<Icon
name={'add'}
onPress={handleUploadAvatar}
style={style.mRegisterUploadIcon}
></Icon>
</View>
)}
</View>
uploadFile: (data) => common({ url: urls.h5.uploadFile, data, method: 'post', headers: { 'content-type': 'multipart/form-data' } }),
?官方RN代碼:
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function ImagePickerExample() {
const [image, setImage] = useState(null);
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.canceled) {
setImage(result.assets[0].uri);
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
}
后端node接收文件上傳:
const multer = require('multer')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const NODE_ENV = process.env.NODE_ENV || 'development'
let tempPath = ''
if (NODE_ENV === 'development') {
tempPath = '/temp/uploadForDev/upload'
} else if (NODE_ENV === 'production') {
tempPath = '/temp/uploadForProd/upload'
} else if (NODE_ENV === 'codesandbox') {
tempPath = 'uploadForCodesandbox/upload'
}
cb(null, tempPath)
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`)
},
})
const uploadImgMulter = multer({ storage })
//上傳
const uploadFile = (req, res) => {
res.send({
code: 200,
data: {
...req.file,
filename: 'upload/' + req.file.filename
},
message: '上傳成功',
})
}
app.post(urls.light.uploadFile, uploadImgMulter.single('file'), (req, res) => commonGroup({ req, res, myRoleGroup: roleGroup.notNeeedLogin, callback: uploadFile }) )
?
chatgpt的回答
?
?expo-image-picker 圖片上傳
要使用Expo的ImagePicker庫進行圖片上傳,您可以按照以下步驟操作。
首先,確保您已在項目中安裝了Expo的ImagePicker庫。
expo install expo-image-picker
然后,您可以使用以下代碼來選擇圖片并上傳:
import React, { useState, useEffect } from 'react';
import { Button, Image, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
const ImagePickerExample = () => {
const [image, setImage] = useState(null);
useEffect(() => {
(async () => {
// 請求權(quán)限
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
console.log('拒絕訪問圖片庫權(quán)限!');
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
// 設(shè)置選擇的圖片
setImage(result.uri);
// 上傳圖片的邏輯
// ...
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="選擇圖片" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200, marginTop: 20 }} />}
</View>
);
};
export default ImagePickerExample;
此示例使用Button和Image組件創(chuàng)建一個簡單的界面,點擊按鈕將觸發(fā)選擇圖片的邏輯。選擇圖片后,將通過設(shè)置useState來更新圖像狀態(tài),并將圖像顯示在屏幕上。
在pickImage函數(shù)中,使用ImagePicker.launchImageLibraryAsync方法來打開本地圖庫,您可以根據(jù)自己的需求配置options參數(shù)。選擇圖片后,將在控制臺中打印結(jié)果。您可以根據(jù)需要將選中的圖片上傳到服務(wù)器。
請注意,在使用ImagePicker之前,您需要在app.json文件中的expo.permissions字段中添加相應(yīng)的權(quán)限(例如:READ_EXTERNAL_STORAGE)。
希望這可以幫助到您!如果您有任何其他問題,請隨時提問。
使用圖片絕對路徑,把圖片上傳到后端
要使用圖片的絕對路徑將其上傳到后端,您可以使用FormData
對象來創(chuàng)建一個包含文件的表單數(shù)據(jù),并使用fetch
函數(shù)將該數(shù)據(jù)發(fā)送到后端。
以下是一個使用絕對路徑上傳圖片的示例代碼:
import React, { useState } from 'react';
import { Button, Image, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
const ImagePickerExample = () => {
const [image, setImage] = useState(null);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
// 設(shè)置選擇的圖片
setImage(result.uri);
// 上傳圖片到后端
uploadImage(result.uri);
}
};
const uploadImage = async (uri) => {
// 創(chuàng)建FormData對象
const formData = new FormData();
formData.append('image', { uri, name: 'image.jpg', type: 'image/jpeg' });
try {
const response = await fetch('https://your-api-endpoint', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
if (response.status === 200) {
console.log('圖片上傳成功');
} else {
console.log('圖片上傳失敗');
}
} catch (error) {
console.log('上傳圖片時出錯', error);
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="選擇圖片" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200, marginTop: 20 }} />}
</View>
);
};
export default ImagePickerExample;
在uploadImage
函數(shù)中,我們創(chuàng)建了一個FormData
對象并使用append
方法將文件添加到表單數(shù)據(jù)中。我們指定了文件的名稱為image.jpg
,文件類型為image/jpeg
。然后,我們使用fetch
函數(shù)將該表單數(shù)據(jù)發(fā)送到后端的API端點。
請將https://your-api-endpoint
替換為您實際的后端API的地址。您還可以根據(jù)需要配置其他請求參數(shù)。
注意:在使用fetch
發(fā)送請求時,確保設(shè)置了正確的請求頭Content-Type
為multipart/form-data
,以便服務(wù)器正確解析請求。
希望這可以幫助到您!如果您有任何其他問題,請隨時提問。
?參考鏈接:
https://chat.xutongbao.top/文章來源:http://www.zghlxwxcb.cn/news/detail-615781.html
https://docs.expo.dev/versions/latest/sdk/imagepicker/
到了這里,關(guān)于React Native expo項目使用expo-image-picker上傳圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!