Skip to content

Instantly share code, notes, and snippets.

@AmirMahdyJebreily
Created September 16, 2023 14:08
Show Gist options
  • Save AmirMahdyJebreily/e2570611d962d430f09b0e94468848fe to your computer and use it in GitHub Desktop.
Save AmirMahdyJebreily/e2570611d962d430f09b0e94468848fe to your computer and use it in GitHub Desktop.
// Receiving database files from clients via http request
[ParameterRoute(HttpMethod.PUT, "/server/uploadFile/{fileName}")]
public static async Task GetFile(HttpContext ctx)
{
try
{
// Url data
string fileName = ctx.Request.Url.Parameters["fileName"];
// Variabels
string path = "C:\Files\"
// Checking whether the data is chunked or not
if (ctx.Request.ChunkedTransfer)
{
// load chuncked data
bool finalChunk = false;
var dataBuffer = new List<byte>();
while (!finalChunk)
{
Chunk chunk = await ctx.Request.ReadChunk();
try
{
dataBuffer.AddRange(chunk.Data);
}
catch (Exception ex) { throw ex; }
finalChunk = chunk.IsFinalChunk;
}
// save all buffers into a file
File.WriteAllBytes(path, dataBuffer.ToArray());
}
else
{
using (var dataStream = ctx.Request.Data)
{
// read data stream
var dataBuffer = await dataStream.ReadToEndAsync();
try
{
// Saving the data read from the Stream
File.WriteAllBytes(path, dataBuffer.ToArray());
if (!File.Exists(path))
{
throw new Exception("the file wasn't recived.")
}
}
catch (Exception ex) { throw ex; }
}
}
await ctx.Response.Send("the file with was recived.");
ctx.Response.StatusCode = 204;
}
catch (Exception ex)
{
await ctx.Response.Send("500 --===>" + ex.Message);
ctx.Response.StatusCode = 500;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment