How to upload stream of a file to AWS S3 in ASP.NET? The Next CEO of Stack OverflowInterrupt reading incoming request in WCF RESTWCF vs ASP.NET Web APIMultipart upload to Amazon S3 overwrites the last partFile upload in WCF Service (413) Request Entity Too LargeAWS S3 uploadDirectory Drops ConnectionBrowser-based upload - AWS S3 Signed POST - Verify correct file is uploadedIs S3 REST for PUT (direct upload) operation chunked?AWS.S3.upload() 403 Error When Attempting Multipart UploadUpload of file to AWS S3-bucket doesn't workHow to have a WCF RESTful endpoint returning Stream that can also send error message

Why does standard notation not preserve intervals (visually)

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Is HostGator storing my password in plaintext?

Preparing Indesign booklet with .psd graphics for print

How to avoid supervisors with prejudiced views?

How to add tiny 0.5A 120V load to very remote split phase 240v 3 wire well house

Return the Closest Prime Number

Is it professional to write unrelated content in an almost-empty email?

Is there a difference between "Fahrstuhl" and "Aufzug"

How do scammers retract money, while you can’t?

How did people program for Consoles with multiple CPUs?

Bold, vivid family

How do I go from 300 unfinished/half written blog posts, to published posts?

If a black hole is created from light, can this black hole then move at speed of light?

Should I tutor a student who I know has cheated on their homework?

Which tube will fit a -(700 x 25c) wheel?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

What does "Its cash flow is deeply negative" mean?

Novel about a guy who is possessed by the divine essence and the world ends?

Skipping indices in a product

Why does the UK parliament need a vote on the political declaration?

How to start emacs in "nothing" mode (`fundamental-mode`)

Limits on contract work without pre-agreed price/contract (UK)

Is there an analogue of projective spaces for proper schemes?



How to upload stream of a file to AWS S3 in ASP.NET?



The Next CEO of Stack OverflowInterrupt reading incoming request in WCF RESTWCF vs ASP.NET Web APIMultipart upload to Amazon S3 overwrites the last partFile upload in WCF Service (413) Request Entity Too LargeAWS S3 uploadDirectory Drops ConnectionBrowser-based upload - AWS S3 Signed POST - Verify correct file is uploadedIs S3 REST for PUT (direct upload) operation chunked?AWS.S3.upload() 403 Error When Attempting Multipart UploadUpload of file to AWS S3-bucket doesn't workHow to have a WCF RESTful endpoint returning Stream that can also send error message










0















I am very much new to AWS S3 and trying to upload large file by chunked process. From UI, i am sending the file's chunked data(blob) to WCF service from where i will upload it to S3 using MultiPartAPI. Note that, the file can be in GB's. That's why i am making chunks of the file and uploading it to S3.



public UploadPartResponse UploadChunk(Stream stream, string fileName, string uploadId, List<PartETag> eTags, int partNumber, bool lastPart)

stream.Position = 0; // Throwing Exceptions

//Step 1: build and send a multi upload request
if (partNumber == 1)

var initiateRequest = new InitiateMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName
;

var initResponse = _s3Client.InitiateMultipartUpload(initiateRequest);
uploadId = initResponse.UploadId;


//Step 2: upload each chunk (this is run for every chunk unlike the other steps which are run once)
var uploadRequest = new UploadPartRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartNumber = partNumber,
InputStream = stream,
IsLastPart = lastPart,
PartSize = stream.Length // Throwing Exceptions
;

var response = _s3Client.UploadPart(uploadRequest);

//Step 3: build and send the multipart complete request
if (lastPart)

eTags.Add(new PartETag

PartNumber = partNumber,
ETag = response.ETag
);

var completeRequest = new CompleteMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartETags = eTags
;

try

_s3Client.CompleteMultipartUpload(completeRequest);

catch

//do some logging and return null response
return null;



response.ResponseMetadata.Metadata["uploadid"] = uploadRequest.UploadId;
return response;



Here, stream.Position = 0 and stream.Length throwing exceptions like below:




at
System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()




Then i saw that stream.CanSeek is false.



Do i need to actually buffer the entire stream, loading it into memory in advance to make it working?



Update: I am doing below and it's working but don't know whether it is efficient or not.



 var ms = new MemoryStream();
stream.CopyTo(ms);
ms.Position = 0;


Is there any other way to do this? Thanks in advance.










share|improve this question
























  • I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

    – mahlatse
    Mar 8 at 15:46















0















I am very much new to AWS S3 and trying to upload large file by chunked process. From UI, i am sending the file's chunked data(blob) to WCF service from where i will upload it to S3 using MultiPartAPI. Note that, the file can be in GB's. That's why i am making chunks of the file and uploading it to S3.



public UploadPartResponse UploadChunk(Stream stream, string fileName, string uploadId, List<PartETag> eTags, int partNumber, bool lastPart)

stream.Position = 0; // Throwing Exceptions

//Step 1: build and send a multi upload request
if (partNumber == 1)

var initiateRequest = new InitiateMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName
;

var initResponse = _s3Client.InitiateMultipartUpload(initiateRequest);
uploadId = initResponse.UploadId;


//Step 2: upload each chunk (this is run for every chunk unlike the other steps which are run once)
var uploadRequest = new UploadPartRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartNumber = partNumber,
InputStream = stream,
IsLastPart = lastPart,
PartSize = stream.Length // Throwing Exceptions
;

var response = _s3Client.UploadPart(uploadRequest);

//Step 3: build and send the multipart complete request
if (lastPart)

eTags.Add(new PartETag

PartNumber = partNumber,
ETag = response.ETag
);

var completeRequest = new CompleteMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartETags = eTags
;

try

_s3Client.CompleteMultipartUpload(completeRequest);

catch

//do some logging and return null response
return null;



response.ResponseMetadata.Metadata["uploadid"] = uploadRequest.UploadId;
return response;



Here, stream.Position = 0 and stream.Length throwing exceptions like below:




at
System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()




Then i saw that stream.CanSeek is false.



Do i need to actually buffer the entire stream, loading it into memory in advance to make it working?



Update: I am doing below and it's working but don't know whether it is efficient or not.



 var ms = new MemoryStream();
stream.CopyTo(ms);
ms.Position = 0;


Is there any other way to do this? Thanks in advance.










share|improve this question
























  • I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

    – mahlatse
    Mar 8 at 15:46













0












0








0


1






I am very much new to AWS S3 and trying to upload large file by chunked process. From UI, i am sending the file's chunked data(blob) to WCF service from where i will upload it to S3 using MultiPartAPI. Note that, the file can be in GB's. That's why i am making chunks of the file and uploading it to S3.



public UploadPartResponse UploadChunk(Stream stream, string fileName, string uploadId, List<PartETag> eTags, int partNumber, bool lastPart)

stream.Position = 0; // Throwing Exceptions

//Step 1: build and send a multi upload request
if (partNumber == 1)

var initiateRequest = new InitiateMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName
;

var initResponse = _s3Client.InitiateMultipartUpload(initiateRequest);
uploadId = initResponse.UploadId;


//Step 2: upload each chunk (this is run for every chunk unlike the other steps which are run once)
var uploadRequest = new UploadPartRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartNumber = partNumber,
InputStream = stream,
IsLastPart = lastPart,
PartSize = stream.Length // Throwing Exceptions
;

var response = _s3Client.UploadPart(uploadRequest);

//Step 3: build and send the multipart complete request
if (lastPart)

eTags.Add(new PartETag

PartNumber = partNumber,
ETag = response.ETag
);

var completeRequest = new CompleteMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartETags = eTags
;

try

_s3Client.CompleteMultipartUpload(completeRequest);

catch

//do some logging and return null response
return null;



response.ResponseMetadata.Metadata["uploadid"] = uploadRequest.UploadId;
return response;



Here, stream.Position = 0 and stream.Length throwing exceptions like below:




at
System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()




Then i saw that stream.CanSeek is false.



Do i need to actually buffer the entire stream, loading it into memory in advance to make it working?



Update: I am doing below and it's working but don't know whether it is efficient or not.



 var ms = new MemoryStream();
stream.CopyTo(ms);
ms.Position = 0;


Is there any other way to do this? Thanks in advance.










share|improve this question
















I am very much new to AWS S3 and trying to upload large file by chunked process. From UI, i am sending the file's chunked data(blob) to WCF service from where i will upload it to S3 using MultiPartAPI. Note that, the file can be in GB's. That's why i am making chunks of the file and uploading it to S3.



public UploadPartResponse UploadChunk(Stream stream, string fileName, string uploadId, List<PartETag> eTags, int partNumber, bool lastPart)

stream.Position = 0; // Throwing Exceptions

//Step 1: build and send a multi upload request
if (partNumber == 1)

var initiateRequest = new InitiateMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName
;

var initResponse = _s3Client.InitiateMultipartUpload(initiateRequest);
uploadId = initResponse.UploadId;


//Step 2: upload each chunk (this is run for every chunk unlike the other steps which are run once)
var uploadRequest = new UploadPartRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartNumber = partNumber,
InputStream = stream,
IsLastPart = lastPart,
PartSize = stream.Length // Throwing Exceptions
;

var response = _s3Client.UploadPart(uploadRequest);

//Step 3: build and send the multipart complete request
if (lastPart)

eTags.Add(new PartETag

PartNumber = partNumber,
ETag = response.ETag
);

var completeRequest = new CompleteMultipartUploadRequest

BucketName = _settings.Bucket,
Key = fileName,
UploadId = uploadId,
PartETags = eTags
;

try

_s3Client.CompleteMultipartUpload(completeRequest);

catch

//do some logging and return null response
return null;



response.ResponseMetadata.Metadata["uploadid"] = uploadRequest.UploadId;
return response;



Here, stream.Position = 0 and stream.Length throwing exceptions like below:




at
System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()




Then i saw that stream.CanSeek is false.



Do i need to actually buffer the entire stream, loading it into memory in advance to make it working?



Update: I am doing below and it's working but don't know whether it is efficient or not.



 var ms = new MemoryStream();
stream.CopyTo(ms);
ms.Position = 0;


Is there any other way to do this? Thanks in advance.







amazon-web-services wcf amazon-s3 aws-sdk-net






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 14:44







Setu Basak

















asked Mar 8 at 14:15









Setu BasakSetu Basak

4,51662648




4,51662648












  • I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

    – mahlatse
    Mar 8 at 15:46

















  • I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

    – mahlatse
    Mar 8 at 15:46
















I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

– mahlatse
Mar 8 at 15:46





I dont think you can modify the stream if you cant seek from it, that seems to be the best way of creating another stream and copying all the data in it,

– mahlatse
Mar 8 at 15:46












1 Answer
1






active

oldest

votes


















0














That's a fair way of doing it, but I opted for a different approach by uploading directly to S3 using signed URLs. This has the benefit of taking some load off of your server, and reducing data transfer.



Depending on your application, it may be worth considering this:



In C# get the Presigned URL:



public string GetPreSignedUrl(string bucketName, string keyPrefix, string fileName)

var client = new AmazonS3Client(_credentials, _region);
var keyName = $"keyPrefix/fileName";
var preSignedUrlRequest = new GetPreSignedUrlRequest()

BucketName = bucketName,
Key = keyName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = (Protocol.HTTPS)
;
return client.GetPreSignedURL(preSignedUrlRequest);



This creates a URL for a client to upload directly to S3, which you need to pass to the UI. Then you can use a multipart upload to the presigned url.



Here is a good example of multipart upload using axious: https://github.com/prestonlimlianjie/aws-s3-multipart-presigned-upload/blob/master/frontend/pages/index.js






share|improve this answer























  • I will try it. Thanks :)

    – Setu Basak
    Mar 9 at 5:40











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065042%2fhow-to-upload-stream-of-a-file-to-aws-s3-in-asp-net%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














That's a fair way of doing it, but I opted for a different approach by uploading directly to S3 using signed URLs. This has the benefit of taking some load off of your server, and reducing data transfer.



Depending on your application, it may be worth considering this:



In C# get the Presigned URL:



public string GetPreSignedUrl(string bucketName, string keyPrefix, string fileName)

var client = new AmazonS3Client(_credentials, _region);
var keyName = $"keyPrefix/fileName";
var preSignedUrlRequest = new GetPreSignedUrlRequest()

BucketName = bucketName,
Key = keyName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = (Protocol.HTTPS)
;
return client.GetPreSignedURL(preSignedUrlRequest);



This creates a URL for a client to upload directly to S3, which you need to pass to the UI. Then you can use a multipart upload to the presigned url.



Here is a good example of multipart upload using axious: https://github.com/prestonlimlianjie/aws-s3-multipart-presigned-upload/blob/master/frontend/pages/index.js






share|improve this answer























  • I will try it. Thanks :)

    – Setu Basak
    Mar 9 at 5:40















0














That's a fair way of doing it, but I opted for a different approach by uploading directly to S3 using signed URLs. This has the benefit of taking some load off of your server, and reducing data transfer.



Depending on your application, it may be worth considering this:



In C# get the Presigned URL:



public string GetPreSignedUrl(string bucketName, string keyPrefix, string fileName)

var client = new AmazonS3Client(_credentials, _region);
var keyName = $"keyPrefix/fileName";
var preSignedUrlRequest = new GetPreSignedUrlRequest()

BucketName = bucketName,
Key = keyName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = (Protocol.HTTPS)
;
return client.GetPreSignedURL(preSignedUrlRequest);



This creates a URL for a client to upload directly to S3, which you need to pass to the UI. Then you can use a multipart upload to the presigned url.



Here is a good example of multipart upload using axious: https://github.com/prestonlimlianjie/aws-s3-multipart-presigned-upload/blob/master/frontend/pages/index.js






share|improve this answer























  • I will try it. Thanks :)

    – Setu Basak
    Mar 9 at 5:40













0












0








0







That's a fair way of doing it, but I opted for a different approach by uploading directly to S3 using signed URLs. This has the benefit of taking some load off of your server, and reducing data transfer.



Depending on your application, it may be worth considering this:



In C# get the Presigned URL:



public string GetPreSignedUrl(string bucketName, string keyPrefix, string fileName)

var client = new AmazonS3Client(_credentials, _region);
var keyName = $"keyPrefix/fileName";
var preSignedUrlRequest = new GetPreSignedUrlRequest()

BucketName = bucketName,
Key = keyName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = (Protocol.HTTPS)
;
return client.GetPreSignedURL(preSignedUrlRequest);



This creates a URL for a client to upload directly to S3, which you need to pass to the UI. Then you can use a multipart upload to the presigned url.



Here is a good example of multipart upload using axious: https://github.com/prestonlimlianjie/aws-s3-multipart-presigned-upload/blob/master/frontend/pages/index.js






share|improve this answer













That's a fair way of doing it, but I opted for a different approach by uploading directly to S3 using signed URLs. This has the benefit of taking some load off of your server, and reducing data transfer.



Depending on your application, it may be worth considering this:



In C# get the Presigned URL:



public string GetPreSignedUrl(string bucketName, string keyPrefix, string fileName)

var client = new AmazonS3Client(_credentials, _region);
var keyName = $"keyPrefix/fileName";
var preSignedUrlRequest = new GetPreSignedUrlRequest()

BucketName = bucketName,
Key = keyName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = (Protocol.HTTPS)
;
return client.GetPreSignedURL(preSignedUrlRequest);



This creates a URL for a client to upload directly to S3, which you need to pass to the UI. Then you can use a multipart upload to the presigned url.



Here is a good example of multipart upload using axious: https://github.com/prestonlimlianjie/aws-s3-multipart-presigned-upload/blob/master/frontend/pages/index.js







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 17:30









Matt DMatt D

1,7021617




1,7021617












  • I will try it. Thanks :)

    – Setu Basak
    Mar 9 at 5:40

















  • I will try it. Thanks :)

    – Setu Basak
    Mar 9 at 5:40
















I will try it. Thanks :)

– Setu Basak
Mar 9 at 5:40





I will try it. Thanks :)

– Setu Basak
Mar 9 at 5:40



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid …


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065042%2fhow-to-upload-stream-of-a-file-to-aws-s3-in-asp-net%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't find variable: document ReactNative Js2019 Community Moderator ElectionReactNative: how to center text?Can't find variable: navigate - ReactNative navigationReact Native error: “Can't find variable: TouchableHighlight”How to use Expo.DocumentPicker.getDocumentAsync properly. [Expo] [ReactNative]Can't find variable: regeneratorRuntime (ReactNative)Reactnative Expo It is advisable for a StartUp?Can't find variable : Self / Can't install firebaseNPM Install Error in installing ReactNative CLIContacts Displaying in App using ReactnativeFacebook login error: can't find variable: Alert

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices