【问题标题】:Flutter http request upload mp3 fileFlutter http请求上传mp3文件
【发布时间】:2020-05-05 15:10:40
【问题描述】:

我正在使用这个 api 上传一个 mp3 文件

使用这个方法

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);
  }

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

【问题讨论】:

  • 这不会解决您的问题,但您应该使用 MultipartFile 的另一个命名构造函数,它接受文件而不是字节。保存读取文件的步骤。

标签: http flutter dart upload


【解决方案1】:

请使用flutter_upload包上传文件

或者使用下面的代码使用 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);
    }
  }

【讨论】:

    【解决方案2】:

    尝试将文件名添加到

    http.MultipartFile.fromBytes()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2018-06-08
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多