如何使用react-native的fetch api将文件上传到服务器以实现类似的功能:
------WebKitFormBoundaryRAxza9ew2ADaYHn5
Content-Disposition: form-data; name="file"; filename="66154520.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryRAxza9ew2ADaYHn5--发布于 2016-11-24 17:41:15
你没有展示任何类型的代码,但理论上...
您应该将url从ImagePicker或CameraRoll (应该类似于file:///storage/emulated/0/Pictures/shj15791-4v61-67g6-z1b6-v8451z956j5k.jpg)传递给formData,然后将其与请求一起传递:
const form = new FormData();
form.append('image', {
uri: "file:///...",
type: 'image/jpg',
name: 'image.jpg',
});
fetch('https://example.com/api/upload', {
method: 'POST',
body: form
});发布于 2020-12-05 18:48:52
这对我很有效。在安卓和iOS上测试了摄像头和图库
const os = Platform.OS
let data = new FormData();
if (os == 'android') {
const fileName = new Date().getTime() + getExtention(mime);
let fileInfo = '';
await RNFS.copyFile(uri, RNFS.CachesDirectoryPath + '/' + fileName).catch(e => {
fileInfo = undefined;
});
if (!fileInfo) {
fileDetail = await RNFS
.stat(RNFS.CachesDirectoryPath + '/' + fileName)
.catch(e => {});
data.append('file', {
name: getFilename(fileDetail.path),
type: payload.file.type,
uri: 'file://' + fileDetail.path,
});
}
} else {
let localPath= uri;
if (!localPath.includes('private')) {
localPath = localPath.replace('/var', '/private/var');
}
data.append('file', {
name: getFilename(localPath),
type: mime,
uri: localPath.replace('file://', ''),
});
} export const getFilename = url => {
return url.substr(url.lastIndexOf('/') + 1);
};
export const getExtention = mime => {
switch (mime) {
case 'application/pdf':
return '.pdf';
case 'image/jpeg':
return '.jpg';
case 'image/jpg':
return '.jpg';
case 'image/png':
return '.png';
default:
return '.jpg';
}
};发布于 2021-05-19 19:21:59
在react-:中,这是您将图像或文件上传到服务器的方式
const data = await this.camera.takePictureAsync(options);
URL = data.uri
const form = new FormData();
form.append('image', {
name: 'image',
type: 'image/jpeg',
uri: URL,
});
axios
.post(`url`, form)
.then(function (response) {
console.log('kkkkkkkkkkkk', response.data);
})
.catch(function (error) {
console.log('errrrrrrrrrrrr', error);
});https://stackoverflow.com/questions/40760931
复制相似问题