我的后端接受用于影像上傳的原始影像和二進制檔案(在 Postman 中作業),但在 React Native 前端我react-native-image-crop-picker用來獲取uri影像等等。
我需要能夠以原始或二進制形式發送影像,而不是將其嵌入到 FormData 中。
我正在使用 Axios 來處理我的請求。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
uri由react-native-image-crop-picker. _ 獲取影像原始資料(BLOB)為
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", [IMG_URI_HERE], true);
xhr.send(null);
});
// Your logic to upload BLOB data to the server
// We're done with the blob, close and release it
blob.close();
uj5u.com熱心網友回復:
根據react-native-image-crop-picker您可以通過在請求物件中設定來獲取base64-encoded字串。includeBase64true
includeBase64 -- bool (默認 false) -- 當設定為 true 時,影像檔案內容將在 data 屬性中以 base64 編碼字串的形式提供。提示:要將此字串用作影像源,請按如下方式使用:<Image source={{uri:
data:${image.mime};base64,${image.data}}} />
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true,
includeBase64: true
}).then(image => {
console.log(image.data);
});
uj5u.com熱心網友回復:
您可以將以下代碼與react-native-image-crop-picker庫和axios庫一起使用。
ImagePicker.openPicker({
compressImageMaxWidth: 300,
compressImageMaxHeight: 300,
mediaType: 'photo',
cropping: true,
})
.then(({ path, mime }) => {
if (path) {
const file = {
uri: path,
name: path,
type: mime,
};
const body = new FormData();
body.append('file', file);
uploadImage(body);
}
})
.catch((e) => {
console.log(e.message);
});
哪里uploadImage有以下實作
const uploadImage = (data) => {
const payload = {
baseURL: AppConfig.BASE_URL,
url: '/image',
method: 'post',
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 120000,
data,
}
axios(payload);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422623.html
標籤:
