簡體   English   中英

Flutter http請求上傳mp3文件

[英]Flutter http request upload mp3 file

我使用這個 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);
  }

但它不起作用,似乎沒有文件上傳,我錯過了什么嗎? 或者有更好的解決方案嗎?

請使用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);
    }
  }

嘗試將文件名添加到

http.MultipartFile.fromBytes()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM