[xmlHttpRequest] [react-native] xhr.upload.onprogress无法使用xhr.send({uri:' file:///...'})

时间:2017-09-01 04:09:53

标签: android react-native youtube xmlhttprequest form-data

我尝试使用youtube v3 API上传视频,查看this示例。

所以,我写了这样的话:



Get-ServiceFabricApplicationStatus




并且它有效,我有var xhr = new XMLHttpRequest(); xhr.open('PUT', this.url, true); xhr.setRequestHeader('Content-Type', this.contentType); <=== video/mp4 xhr.setRequestHeader('Content-Range', 'bytes ' + this.offset + '-' + (end - 1) + '/' + this.filesize); xhr.setRequestHeader('X-Upload-Content-Type', this.filetype); <=== video/mp4 if (xhr.upload) { xhr.upload.addEventListener('progress', this.onProgress); } xhr.onload = this.onContentUploadSuccess_.bind(this); xhr.onerror = this.onContentUploadError_.bind(this); xhr.send({uri: this.file.path}); <=== file:///.....xhr.onload,视频文件已上传到youtube并在那里播放。

但我没有xhr.onerror

我尝试xhr.upload.onprogressxhr.onprogressxhr.upload.onprogress - 所有这些都不起作用。

BUT! 当我使用xhr.upload.addEventListener

&#13;
&#13;
FormData
&#13;
&#13;
&#13;

let data = new FormData(); data.append('File', { uri: source.path, type: source.type, name: source.name }); var xhr = new XMLHttpRequest(); xhr.open('PUT', this.url, true); //xhr.setRequestHeader('Content-Type', this.contentType); //=== comment this, because it throw error 'multipart != video/mp4' //xhr.setRequestHeader('Content-Range', 'bytes ' + this.offset + '-' + (end - 1) + '/' + this.filesize); //=== comment this, because sending data size != filesize xhr.setRequestHeader('X-Upload-Content-Type', this.filetype); if (xhr.upload) { xhr.upload.addEventListener('progress', this.onProgress); } xhr.onload = this.onContentUploadSuccess_.bind(this); xhr.onerror = this.onContentUploadError_.bind(this); xhr.send(data); <==== FormData正在运作。但是后来youtube api返回处理错误,因为它只支持&#39; video / *&#39;和&#39; application / octet-stream&#39;并且不支持&multi39 / form-data&#39;。

我做错了什么以及在xhr.upload.onprogress没有使用xhr.upload.onprogress时我需要做些什么?

P.S。对不起我丑陋的英语

  • react-native v0.47.2
  • node v8.2.1
  • npm v5.3.0

  • 目标平台:Android

  • 开发操作系统:MacOS
  • 构建工具:Android SDK

1 个答案:

答案 0 :(得分:0)

这篇文章是前一阵子,但是尝试一下:

const xhr = new XMLHttpRequest();
xhr.open('PUT', uploadUrl);
xhr.onLoad = this.onContentUploadSuccess_.bind(this);
xhr.onerror = this.onContentUploadError_.bind(this);
...formData here
xhr.send(formData);
if (xhr.upload) {
  xhr.upload.onprogress = ({ total, loaded }) => console.log(loaded / total);
}

将xhr.upload.onprogress放在最后对我有用。检查Firefox docs以获取事件详细信息(如已加载,总计)。确保解构total并加载我上面的方法。