We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

set custom statusText for restuls in upload

Hi, I'm using angular and aspnet core web api in a project.

I need upload a file and process this file.

But whether everything has gone correctly or if I have made an error, I can not get the response message from the server.

For other hand, I've defined the server path in asyncsettings. But... Can I use a custom service for upload the file instead set the saveUrl  asyncsettings?

Thanks

15 Replies

PO Prince Oliver Syncfusion Team March 13, 2019 01:47 AM

HI Manolo, 

Thank you for contacting Syncfusion support. 

The uploader component allows you to modify the file even after uploading to the server, which can be done using success and failure event of the uploader. You need to use the custom headers to send the data from server to client side. While receiving the custom headers in client side it will contains server details along with the sent message. Kindly refer to the following code snippet. 

[html] 
<ejs-uploader #upload id=uploadDefault [asyncSettings]='path' (failure)='onUploadStatus($event)' (success)='onUploadStatus($event)'></ejs-uploader> 
 

[component.ts] 
onUploadStatus(args) { 
    var header = args.response.headers; 
    var statusMessage = header.slice(header.indexOf('status'), header.indexOf('date')); 
    statusMessage = statusMessage.slice(statusMessage.indexOf(',') + 1); 
    args.statusText = statusMessage.trim(); 
} 
 

[server side] 
[AcceptVerbs("Post")] 
public IActionResult Save(IList<IFormFile> UploadFiles) 
{ 
    try 
    { 
        foreach (var file in UploadFiles) 
        { 
            if (UploadFiles != null) 
            { 
                var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); filename = hostingEnv.WebRootPath + $@"{filename}"; 
                if (!System.IO.File.Exists(filename)) 
                { 
                    using (FileStream fs = System.IO.File.Create(filename)) 
                    { 
                        file.CopyTo(fs); fs.Flush(); 
                    } 
                } 
                else 
                { 
                    Response.Clear(); Response.StatusCode = 404; Response.Headers.Add("status", "File Already Exists"); 
                } 
            } 
        } 
    } 
    catch (Exception e) 
    { 
        Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.StatusCode = 400; Response.Headers.Add("status", e.Message); 
    } 
    return Content(""); 
} 
 

Also, instead of using asyncSettings saveUrl property in uploader component, you can use fileSelected event to get the selected file details and set args.cancel = true to prevent the default uploader process. Then use the file data to upload the file to your own custom service. Please refer the following links for customizing the uploader. 


Please let us know if you need any further assistance on this. 

Regards, 
Prince  



MC Manolo Capdevila March 13, 2019 06:19 AM

Hi,

I can't get the response headers in angular.

I attach a simple example

Thanks

Attachment: uploadProblem_4c90061b.zip


MC Manolo Capdevila March 18, 2019 10:40 AM

Any idea?


PO Prince Oliver Syncfusion Team March 19, 2019 01:02 AM

HI Manolo, 

Thank you for your patience. 

We have checked the reported issue in our end and upon validation, we could infer that the issue occurs with WebAPI app in ASP.NET Core 2.2. We were not able to get the custom headers in Core 2.2 WebAPI application and we have raised an issue with AspNetCore regarding this. Kindly refer to the following Issue link: https://github.com/aspnet/AspNetCore/issues/8567  

Until we have a definite solution for this issue, we suggest you use lower dotnet version to resolve this.  

Regards, 
Prince  



MC Manolo Capdevila March 19, 2019 04:08 AM

Ups... I can't reduce the .netcore version...

I follow this thread for the solution

Thanks for your answer


PO Prince Oliver Syncfusion Team March 20, 2019 01:32 AM

Hi Manolo, 

Most Welcome. We are glad to assist you.  

Regards, 
Prince 



MC Manolo Capdevila March 20, 2019 03:48 AM

Is possible use other name in response header name different at status as they suggest?


I try to use different but it doesn't work




PO Prince Oliver Syncfusion Team March 21, 2019 05:46 AM

Hi Manolo, 

We have already tried using a different name and have changed the header name as ("status - custom"). But it is not working in our end too. The custom headers is shown in the chrome browser’s network tab, but it is not obtained in the getAllResponseHeaders() method. 

We have updated the same in the forum. 

Regards, 
Prince 



MC Manolo Capdevila March 22, 2019 08:31 AM

Ok, Thanks...


PO Prince Oliver Syncfusion Team March 25, 2019 01:52 AM

Hi Manolo,  

Most Welcome. We are glad to assist you. We will notify you, if we have a definitive solution for this issue. 

Regards,  
Prince 



MP Megha Patel May 7, 2021 02:04 AM

Hi,

I called the uploading method. I didn't get the header value. [Status]

  [HttpPost]
        [Route("Save")]
        public async Task Save(IList chunkFile)
        {
            try
            {
                var isChunkFile = false;
                foreach (var file in chunkFile)
                {
                    var ProductName = HttpContext.Request.Form["ProductName"];
                    var ProductReleaseNo = HttpContext.Request.Form["ProductReleaseNo"];
                    isChunkFile = true;

                    var httpPostedChunkFile = HttpContext.Request.Form.Files["chunkFile"];



                    var chunkIndex = HttpContext.Request.Form["chunk-index"];

                    var totalChunk = HttpContext.Request.Form["total-chunk"];
                    if (ProductName != "" && ProductReleaseNo != "")
                    {
                        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;
                                    //sha256.TransformBlock(byteArr, 0, bytesToCopy, byteArr, 0);
                                }
                            }

                            if (Convert.ToInt32(chunkIndex) == Convert.ToInt32(totalChunk) - 1)
                            {

                                String strorageconn = Sensit.Activation.API.Helpers.Constants.AzureConnectionString;
                                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(strorageconn);

                                var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

                                CloudBlobContainer container = cloudBlobClient.GetContainerReference("clickonce-app-container");

                                CloudBlobDirectory folder = container.GetDirectoryReference(ProductName);
                                await container.CreateIfNotExistsAsync();

                                CloudBlobDirectory ReleaseFolder = folder.GetDirectoryReference(ProductReleaseNo);
                                await container.CreateIfNotExistsAsync();

                                CloudBlockBlob blockBlob = ReleaseFolder.GetBlockBlobReference(httpPostedChunkFile.FileName);
                                await container.CreateIfNotExistsAsync();

                                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);
                                    // Get All Bytes Hash generated
                                    bytes = GetHashSha256(content);
                                    var UploadFileSHA256 = BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();


                                    content = new byte[] { };
                                    await blockBlob.UploadFromStreamAsync(fileStreams);
                                    Response.Headers.Add("status", "Successnew");
                                }
                            }
                        }
                        Response.Clear();
                        HttpContext.Response.StatusCode = 200;
                        HttpContext.Response.Headers.Add("Status", "Success");
                    }
                    else
                    {
                        Response.Clear();
                        HttpContext.Response.StatusCode = 400;                        
                    }
                }
            }
            catch (Exception e)
            {
                content = new byte[] { };
                Response.Clear();
                HttpContext.Response.StatusCode = 400;
                HttpContext.Response.Headers.Add("Status", "Failed");
            }
        }


In angular 
 <ejs-uploader #defaultupload id='fileupload' (failure)="OnUploadSuccessorFailure($event)"
                            (success)="OnUploadSuccessorFailure($event)" maxFileSize='4294967295' [asyncSettings]='path'
                            [autoUpload]='autoUpload' (pausing)='onPausing($event)' (resuming)='onResuming($event)'
                            (removing)='onFileRemove($event)' (change)="change($event);" multiple='false'
                            (chunkSuccess)='chunkSuccess($event)' (chunkUploading)='onChunkuploading($event)'
                            (chunkFailure)='onfailure($event)'>
                        ejs-uploader>


On Angular Side
  public onfailure(argsany): void {
     alert(JSON.stringify(args));
}


BC Berly Christopher Syncfusion Team May 7, 2021 09:46 AM

Hi Megha, 
  
Currently we are working on the reported issue. So, we will validate and update the further details in two business days (11th May 2021).  
  
Regards, 
Berly B.C 



BC Berly Christopher Syncfusion Team May 11, 2021 09:40 AM

Hi Megha, 
  
We have checked the reported issue. When we send the custom header on Angular + MVC backend application, the header will not be received in the success and failure event arguments due to browser CORS issue. So, we suggest you to enable any browser CORS extension to get all the custom header in the failure and success events.  
  
Screenshot in success event: 
 
  
Screenshot in failure event: 
v 
  
Regards, 
Berly B.C 



AM Armando Monjane September 6, 2021 01:33 AM

Hi Syncfusion Team,


Has this issue been resolved?

I'm currently using "syncfusion/ej2-angular-inputs": "^19.2.55" and i still cannot get custom response headers on the front-end.

I'm using angular on front-end and .net core for the web api.


Regards



GK Gunasekar Kuppusamy Syncfusion Team September 7, 2021 11:50 AM

Hi Armand,

Greetings from Syncfusion support.

We have prepared a sample for your requirement using the latest version of uploader.

In this sample, we have passed custom response headers from .net core web API to the uploader component.

Angular Sample: https://stackblitz.com/edit/angular-azypid?file=app.component.html

.Net Core API :

If you still facing the issue, we suggest you to enable any browser CORS extension to get all the custom header in the failure and success events.  

Please check the sample and let us know if the sample meets your requirement.

Regards,
Gunasekar


Loader.
Live Chat Icon For mobile
Up arrow icon