Flutter http请求上传mp3文件 [英] Flutter http request upload mp3 file

查看:71
本文介绍了Flutter http请求上传mp3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个api上传mp3文件

Im using this api to upload a mp3 file

使用这种方法

Future<void> uploadRecord(String matchId, String filePath) async {
    Uri url = Uri.parse(
        Urls.baseurl + EndPoints.uploadRecordEndPoint + '${auth.token}');


    final request = http.MultipartRequest('POST', url)
      ..fields['match_id'] = matchId
      ..files.add(http.MultipartFile.fromBytes(
          'file', await File.fromUri(Uri(path: filePath)).readAsBytes(),
          contentType: MediaType('audio', 'mpeg')));
    final response = await request.send();
    final responseStr = await response.stream.bytesToString();

    print(responseStr);
  }

但它不起作用,似乎没有文件上传,我错过了什么吗?或者有更好的解决方案吗?

but it doesn't work, it seems that no file uploading, am i missing something ? or is there any better solution ?

推荐答案

请使用 flutter_upload 包上传文件

或者使用下面的代码使用 multipart 上传文件:

Or use below code for uploading the file using multipart :

static Future<String> fileUploadMultipart(
      {File file, OnUploadProgressCallback onUploadProgress}) async {
    assert(file != null);

    final url = '$baseUrl/api/file';

    final httpClient = getHttpClient();

    final request = await httpClient.postUrl(Uri.parse(url));

    int byteCount = 0;

    var multipart = await http.MultipartFile.fromPath(fileUtil.basename(file.path), file.path);

    // final fileStreamFile = file.openRead();

    // var multipart = MultipartFile("file", fileStreamFile, file.lengthSync(),
    //     filename: fileUtil.basename(file.path));

    var requestMultipart = http.MultipartRequest("", Uri.parse("uri"));

    requestMultipart.files.add(multipart);

    var msStream = requestMultipart.finalize();

    var totalByteLength = requestMultipart.contentLength;

    request.contentLength = totalByteLength;

    request.headers.set(
        HttpHeaders.contentTypeHeader, requestMultipart.headers[HttpHeaders.contentTypeHeader]);

    Stream<List<int>> streamUpload = msStream.transform(
      new StreamTransformer.fromHandlers(
        handleData: (data, sink) {
          sink.add(data);

          byteCount += data.length;

          if (onUploadProgress != null) {
            onUploadProgress(byteCount, totalByteLength);
            // CALL STATUS CALLBACK;
          }
        },
        handleError: (error, stack, sink) {
          throw error;
        },
        handleDone: (sink) {
          sink.close();
          // UPLOAD DONE;
        },
      ),
    );

    await request.addStream(streamUpload);

    final httpResponse = await request.close();
//
    var statusCode = httpResponse.statusCode;

    if (statusCode ~/ 100 != 2) {
      throw Exception('Error uploading file, Status code: ${httpResponse.statusCode}');
    } else {
      return await readResponseAsString(httpResponse);
    }
  }

这篇关于Flutter http请求上传mp3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆