namespace CoreHostedFileUpload.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SampleDataController : ControllerBase
{
public static byte[] content = new byte[] { };
[HttpPost("[action]")]
public async Task Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
{
try
{
const string accountName = "****"; // Provide the account name
const string key = "****"; // Provide the account key
var storageCredentials = new StorageCredentials(accountName, key);
var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var isChunkFile = false;
...
if(UploadFiles != null && !isChunkFile)
{
foreach (var file in UploadFiles)
{
var container = cloudBlobClient.GetContainerReference("filo");
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var httpPostedFile = HttpContext.Request.Form.Files["UploadFiles"];
var blob = container.GetBlockBlobReference(httpPostedFile.FileName);
using (var stream = file.OpenReadStream())
{
await blob.UploadFromStreamAsync(stream);
}
}
}
}
catch (Exception e)
{
content = new byte[] { };
Response.Clear();
Response.StatusCode = 204;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
}
}
|
@using System.IO @{ var path = "/uploads/testfolder/"; <SfUploader AutoUpload="true"> <UploaderEvents ValueChange="@(e => OnChangeUploadFiles(e, path))">UploaderEvents> SfUploader> } @code { private void OnChangeUploadFiles(Syncfusion.Blazor.Inputs.UploadChangeEventArgs args, string path) { foreach (var file in args.Files) { string qualifiedfilename = @"wwwroot" + path + file.FileInfo.Name.ToLower(); FileStream filestream = new FileStream(qualifiedfilename, FileMode.Create, FileAccess.Write); file.Stream.WriteTo(filestream); filestream.Close(); file.Stream.Close(); } } }Cheers,
<SfUploader ID="UploadFiles" AutoUpload="true">
<UploaderAsyncSettings SaveUrl="api/SampleData/Save"></UploaderAsyncSettings>
<UploaderEvents FileSelected="@Selected"></UploaderEvents>
</SfUploader>
@code{
void Selected(SelectedEventArgs args)
{
args.CurrentRequest = new List<object> { new { container = "containerName" } };
}
} |
|
|
<SfUploader ID="UploadFiles" AutoUpload="true">
<UploaderEvents ValueChange="changeEvent"></UploaderEvents>
</SfUploader>
@code {
public async Task changeEvent(UploadChangeEventArgs args)
{
foreach (var file in args.Files)
{
const string accountName = "***"; // Provide your accountName
const string key = "***"; // Provide your account key
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("filo"); // Provide your container name
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetBlockBlobReference(file.FileInfo.Name);
await blob.UploadFromStreamAsync(file.Stream);
}
}
}
|
[HttpPost("[action]")]
public async Task Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
{
try
{
const string accountName = "****"; // Provide the account name
const string key = "****"; // Provide the account key
var storageCredentials = new StorageCredentials(accountName, key);
var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var isChunkFile = false;
foreach (var file in chunkFile)
{
isChunkFile = true;
var httpPostedChunkFile = HttpContext.Request.Form.Files["chunkFile"];
var chunkIndex = HttpContext.Request.Form["chunk-index"];
var totalChunk = HttpContext.Request.Form["total-chunk"];
using (var fileStream = file.OpenReadStream())
{
if (Convert.ToInt32(chunkIndex) <= Convert.ToInt32(totalChunk))
{
var streamReader = new MemoryStream();
fileStream.CopyTo(streamReader);
var byteArr = streamReader.ToArray();
if(content.Length > 0)
{
content = content.Concat(byteArr).ToArray();
}
else
{
content = byteArr;
}
}
if (Convert.ToInt32(chunkIndex) == Convert.ToInt32(totalChunk) - 1)
{
var container = cloudBlobClient.GetContainerReference("filo");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(httpPostedChunkFile.FileName);
using (FileStream fileStreams = new FileStream(httpPostedChunkFile.FileName, FileMode.Create))
{
for (int i = 0; i < content.Length; i++)
{
fileStreams.WriteByte(content[i]);
}
fileStreams.Seek(0, SeekOrigin.Begin);
content = new byte[] { };
await blockBlob.UploadFromStreamAsync(fileStreams);
}
}
}
}
if(UploadFiles != null && !isChunkFile)
{
foreach (var file in UploadFiles)
{
var container = cloudBlobClient.GetContainerReference("filo");
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var httpPostedFile = HttpContext.Request.Form.Files["UploadFiles"];
var blob = container.GetBlockBlobReference(httpPostedFile.FileName);
using (var stream = file.OpenReadStream())
{
await blob.UploadFromStreamAsync(stream);
}
}
}
}
catch (Exception e)
{
content = new byte[] { };
Response.Clear();
Response.StatusCode = 204;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
}
}
In this code file first upload in project folder then upload on azure. i want to directly upload on azure not need to save into folder.
<SfUploader ID="UploadFiles" AutoUpload="true">
<UploaderEvents ValueChange="changeEvent"></UploaderEvents>
</SfUploader>
@code {
public async Task changeEvent(UploadChangeEventArgs args)
{
foreach (var file in args.Files)
{
const string accountName = "***"; // Provide your accountName
const string key = "***"; // Provide your account key
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("filo"); // Provide your container name
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetBlockBlobReference(file.FileInfo.Name);
await blob.UploadFromStreamAsync(file.Stream);
}
}
} |
public async Task Save(IList<IFormFile> UploadFiles)
{
try
{
foreach (var file in UploadFiles)
{
const string accountName = "***"; // Provide your accountName
const string key = "***"; // Provide your account key
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("filo"); // Provide your container name
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetBlockBlobReference(file.FileName);
using (var stream = file.OpenReadStream())
{
await blob.UploadFromStreamAsync(stream);
}
}
} |
|
foreach (var file in chunkFile)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.ContentRootPath + $@"\{filename}" |
var container = cloudBlobClient.GetContainerReference("filo");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(httpPostedChunkFile.FileName); |
await blockBlob.UploadFromStreamAsync(fileStream); |
Hi Sureshkumar ,
another problem has arisen with your solution, please have a look to your answer from February 24, 2021 11:58 AM
Concerning question 3 :
The problem with this solution is that it always claims SUCCESS (args.StatusText "file uploaded successfully"), even if we throw a manual exception in the controller to indicate something went wrong in the business-logic (e.g. try to overwrite an existing file or maximum allowed files per folder reached) :
How can we catch the individual exeption-message of the controller (backend) in the Blazor-component (SFUploader, frontend)?
Cheers,
Volker
catch (Exception e)
{
Response.Clear();
Response.StatusCode = 400;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
} |
Hi Deepak,
thank you.
But how can we add some custom details that are visible in the blazor-component (eg. a short message or a custom error number) WHAT caused the error in the controller, not THAT an error has happened?
e.g. only 3 documents allowed per folder (checked in the business logic of our Data Access Layer before uploading, not checking in the Blazor Component, so we have to give the component a hint, what went wrong)
How can we talk from the controller to the component (unidirectional)?
Cheers,
Volker
catch (Exception e)
{
Response.Clear();
Response.StatusCode = 400;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
Response.Headers.Add("ID", "Maximum Uploaded files reached");
} |
<SfUploader ID="UploadFiles" AutoUpload="true">
<UploaderAsyncSettings SaveUrl="api/SampleData/Save"></UploaderAsyncSettings>
<UploaderEvents FileSelected="@Selected" Success="@FileSuccess" OnFailure="@FailureHandler"></UploaderEvents>
</SfUploader>
<p>key value is: @key</p>
<p>pair value is: @value</p>
@code{
public string key { get; set; } = "";
public string value { get; set; } = "";
void Selected(SelectedEventArgs args)
{
args.CurrentRequest = new List<object> { new { container = "containerName" } };
}
public void FileSuccess(SuccessEventArgs args)
{
}
public void FailureHandler(FailureEventArgs args)
{
var customHeader = new string[] { };
customHeader = args.Response.Headers.Split(new Char[] { '\n' }); // To split the response header values
for (var i = 0; i < customHeader.Length; i++)
{
if (customHeader[i].Split(new Char[] { ':' })[0] == "id")
{
key = customHeader[i].Split(new Char[] { ':' })[0]; // To get the key pair of provided custom data in header
value = customHeader[i].Split(new Char[] { ':' })[1].Trim(); // To get the value for the key pair of provided custom data in header
}
}
}
} |
Hello Syncfusion people,
I'm trying to upload big files to my blob storage for a while and still I don't see any working solution from Syncfusion.
Yes, the chunck upload works, but the crazy thing is that that method uploads the upload file to the root of the server and then copies it to the blobstorage and leaves the uploaded file behind in the root of the server.
I guess this is what nobody wants.
Please advise.
Best,
Pete
public async Task Save(IList<IFormFile> UploadFiles)
{
var ContainerName = Response.HttpContext.Request.Headers["container"].ToString();
try
{
if (false)
{
throw new InvalidOperationException("Max allowed files erros");
}
else
{
foreach (var file in UploadFiles)
{
const string accountName = "***"; // Provide your accountName
const string key = "***"; // Provide your account key
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("filo"); // Provide your container name
await container.CreateIfNotExistsAsync();
await container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blob = container.GetBlockBlobReference(file.FileName);
using (var stream = file.OpenReadStream())
{
await blob.UploadFromStreamAsync(stream);
}
var filename = hostingEnv.ContentRootPath + $@"\{file.FileName}";
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
}
}
} |