【问题标题】:How to upload video in react-native?如何在 react-native 中上传视频?
【发布时间】:2021-02-27 16:29:45
【问题描述】:

我想将使用“ImagePicker”挑选的视频上传到我的服务器,下面的代码不起作用?问题是什么?

const handleUploadVideo = (video) => {
console.log(video) //{path:"/storage/emulated/0/WhatsApp/Media/WhatsApp 
                     Video/VID-20201107-WA0004.mp4"
                     uri: "content://media/external/video/media/4264"
const data = new FormData();
data.append('file', {
  name: 'VID-20201107-WA0004.mp4',
  type: 'video/mp4',
  uri: video.uri,
});

fetch('https://staging-api.media.com/api/upload', {
  method: 'POST',
  body: data,
})
  .then((response) => response.json())
  .then((response) => {
    console.log('upload succes', response);
    alert('Upload success!');
    this.setState({photo: null});
  })
  .catch((error) => {
    console.log('upload error', error);
    alert('Upload failed!');
  });

};

执行代码时,没有响应,什么都没有发生

【问题讨论】:

  • 您需要告诉我们是什么问题。当您尝试该代码时会发生什么?您收到错误消息吗?控制台打印了什么?

标签: react-native axios fetch


【解决方案1】:

在 Flutter 中,可以使用MultipartRequest 上传文件。

从上面的链接附加一个sniper。

var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
  ..fields['user'] = 'nweiz@google.com'
  ..files.add(await http.MultipartFile.fromPath(
      'package', 'build/package.tar.gz',
      contentType: MediaType('application', 'x-tar')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

你的例子:

 var uri = Uri.parse("https://staging-api.media.com/api/upload");
    var request = new MultipartRequest("POST", uri);

    var multipartFile = await MultipartFile.fromPath("package", "/storage/emulated/0/WhatsApp/Media/WhatsApp 
                     Video/VID-20201107-WA0004.mp4");
    request.files.add(multipartFile);

    StreamedResponse response = await request.send();
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });

【讨论】:

    【解决方案2】:
    const handleUploadVideo = (video) => {
    console.log(video);
    const data = new FormData();
    
    data.append('file', {
      name: 'VID-20201107-WA0004.mp4',
      type: 'video/mp4',
      uri: video.uri,
    });
    
    fetch('https://staging-api/api/youtube/upload', {
      method: 'POST',
      body: data,
    })
      .then((response) => response.json())
      .then((response) => {
        console.log('upload succes', response);
        alert('Upload success!');
      })
      .catch((error) => {
        console.log('upload error', error);
        alert('Upload failed!');
      });
    };
    

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 2020-08-16
      • 2019-04-28
      • 1970-01-01
      • 2020-03-06
      • 2021-09-18
      • 2018-08-09
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多