簡體   English   中英

通過 http flutter 上傳圖片時是否可以顯示進度條?

[英]Is it possible to show progress bar when upload image via http flutter?

我正在開發一個將圖像上傳到Amazon S3 bucket的應用程序,而不僅僅是顯示Spinner ,我希望能夠獲得關於該上傳狀態的Progress

我正在使用Package:httpMultipartRequest上傳文件。 我已成功上傳文件,但我想獲取正在上傳的文件的進度 我怎樣才能做到這一點? 我當前的代碼看起來像這樣。

  static Future<bool> uploadFile({@required userId, @required albumId, @required data, @required fileName}) async{

    const _accessKeyId = 'AKIAVV**********';
    const _secretKeyId = 'iyBmdn6v***************************';
    const _region = 'us-east-1';
    const _s3Endpoint = 'https://myalbums-content.s3.amazonaws.com';

    final file = data;
    var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
    final length = await file.length();

    final uri = Uri.parse(_s3Endpoint);
    final req = http.MultipartRequest("POST", uri);

    var multipartFile =  http.MultipartFile('file', stream, length,
       contentType: new MediaType('image','JPG'));

    final policy = Policy.fromS3PresignedPost(userId.toString() +'/'+ albumId.toString() +'/'+ fileName,
        'myalbums-content', _accessKeyId, 15, length, region: _region);

    final key = SigV4.calculateSigningKey(_secretKeyId, policy.datetime, _region, 's3');
    final signature = SigV4.calculateSignature(key, policy.encode());
    
    req.files.add(multipartFile);
    req.fields['key'] = policy.key;
    req.fields['acl'] = 'public-read';
    req.fields['X-Amz-Credential'] = policy.credential;
    req.fields['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
    req.fields['X-Amz-Date'] = policy.datetime;
    req.fields['Policy'] = policy.encode();
    req.fields['X-Amz-Signature'] = signature;

    try {
      final res = await req.send();

      if(res.statusCode == 204){
        return true;
      } else {
        return false;
      }
    } catch (e) {
      print('Network issue: '+e.toString());
      return false;
    }
  }

先感謝您。

在 Github 上查看示例。 它顯示了如何使用 Stream 上傳文件。 如果您公開 stream 字節上傳到您的 Widget,您應該能夠使用 ProgressIndicator 將字節總數與 Stream 中的值進行比較。

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

req.send還返回一個可能更容易實現的StreamedResponse

暫無
暫無

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

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