我目前正在使用base64
编码上传视频和图像,但强烈建议使用其他方法。我正在使用RNFetchBlob
读取编码文件,然后将其附加到SuperAgent
进行上传。我已经看到了一些使用FormData附加文件的示例,但是找不到完整的工作示例。如果有人可以提供有关如何实现此目标的代码示例,我将不胜感激。
RNFetchBlob.fs.readFile(filePath, 'base64')
.then((base64data) => {
let base64Image = `data:video/mp4;base64,${base64data}`;
let uploadRequest = superagent.post(uploadURL)
uploadRequest.attach('file',base64Image)
Object.keys(params).forEach((key) => {
uploadRequest.field(key,params[key])
})
uploadRequest.on('progress', function(e) {
this.props.setVideoUploadProgress(e.percent)
}.bind(this))
uploadRequest.end((err,resp) => {
})
})
答案 0 :(得分:0)
我正在使用react-native-image-picker
来允许用户选择或录制视频,这为我提供了视频文件路径的URI。然后,我使用RNFetchBlob
将其上传到服务器。
RNFetchBlob.fetch('POST', 'Upload API endpoint', {
...this.getHeader(),
'Content-Type': 'multipart/form-data'
// Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
// Or simply wrap the file path with RNFetchBlob.wrap().
}, [
// element with property `filename` will be transformed into `file` in form data
{ name: 'file', filename: 'video.mp4', data: RNFetchBlob.wrap(this.state.videoUri) },
// custom content type
]).uploadProgress({ interval: 250 }, (written, total) => {
let uploaded = (written / total) * 100
this.setState({
uploadProgress: uploaded.toFixed(1)
})
})
.then((response) => {
if (response.ok) {
this.setState({
uploading: false,
uploadSuccess: true,
uploadFailed: false,
})
}
}).catch((err) => {
this.setState({
uploading: false,
uploadSuccess: false,
uploadFailed: true,
})
})