Streaming files from amazon s3

后端 未结 1 997
太阳男子
太阳男子 2021-02-06 14:59

I have a problem trying to stream files from amazon s3. Basically, I have files stored on amazom s3, I can\'t provide direct access to these files as users need to be authentica

相关标签:
1条回答
  • 2021-02-06 15:38

    You can stream the file from Amazon S3 to the client through your server without downloading the file to your server, by opening a stream to the Amazon S3 file then read from it and write on the client stream (buffer by buffer).

    Sample Code:

    byte[] buffer = new byte[BUFFER_SIZE];                
    GetObjectRequest getObjRequest = new GetObjectRequest().WithBucketName(Bucket_Name).WithKey(Object_Key);
    
    using (GetObjectResponse getObjRespone = amazonS3Client.GetObject(getObjRequest))
    using (Stream amazonStream = getObjRespone.ResponseStream)
    {
        int bytesReaded = 0;        
        Response.AddHeader("Content-Length", getObjRespone.ContentLength.ToString());
    
        while ((bytesReaded = amazonStream.Read(buffer, 0, buffer.Length)) > 0 && Response.IsClientConnected)
        {
            Response.OutputStream.Write(buffer, 0, bytesReaded);
            Response.OutputStream.Flush();
            buffer = new byte[BUFFER_SIZE];
        }
    }
    
    0 讨论(0)
提交回复
热议问题