File upload not working in asp.net core 3.1 using handler

Dear sir/ma,


I have tried all the answers posted on your forum but without success. File upload will be successful if I use the following code

@{
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" };
}
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" multiple="false" autoUpload="false"></ejs-uploader>


but if I use handler no file will be posted. (Error report: File failed to upload)

@{

    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings
    {
        SaveUrl = "http://localhost:44396/Index?handler=Save",
        RemoveUrl = "http://localhost:44396/Index?handler=Remove"
    };
}
@Html.AntiForgeryToken()
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" multiple="false" autoUpload="false"></ejs-uploader>

<script>
    function addTokens(args) {
        args.currentRequest.setRequestHeader('XSRF-TOKEN', document.getElementsByName('__RequestVerificationToken')[0].value);
    }
</script>

PageModel Code:

public IActionResult OnPostSave(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 = 204;
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists.";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "No Content";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
            return Content("");
        }

All other configurations have been done.

Thanks



11 Replies

PM Ponmani Murugaiyan Syncfusion Team April 13, 2021 10:14 AM UTC

Hi Olumuyiwa, 

Thanks for contacting Syncfusion support. 

Based on your requirement we have prepared the sample with Razor pages in ASP.Net core using AntiForgeryTokens. Please refer the below code block. 

[Index.cshtml]  

@{  
    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "http://localhost:50707/Index?handler=Save", RemoveUrl = "http://localhost:50707/Index?handler=Remove" };  
}  
  
@Html.AntiForgeryToken()  
  
<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" multiple="false" autoUpload="false" uploading="addTokens"></ejs-uploader>  
  
  
<script>  
    function addTokens(args) {  
        args.currentRequest.setRequestHeader('XSRF-TOKEN', document.getElementsByName('__RequestVerificationToken')[0].value);  
    }  
</script>  

[Startup.cs]  

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddMvc().AddJsonOptions(x =>  
    {  
        x.SerializerSettings.ContractResolver = new DefaultContractResolver();  
    });  
    services.AddAntiforgery(o => o.HeaderName = "xsrf-token");  
}  


[Index.cshtml.cs]  
 
[AcceptVerbs("Post")]  
public IActionResult OnPostSave(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 = 204;  
                    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists.";  
                }  
            }  
        }  
    }  
    catch (Exception e)  
    {  
        Response.Clear();  
        Response.ContentType = "application/json; charset=utf-8";  
        Response.StatusCode = 204;  
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "No Content";  
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;  
    }  
    return Content("");  
}  
[AcceptVerbs("Post")]  
public IActionResult OnPostRemove(IList<IFormFile> UploadFiles)  
{  
    try  
    {  
        foreach (var file in UploadFiles)  
        {  
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');  
            var filePath = Path.Combine(hostingEnv.WebRootPath);  
            var fileSavePath = filePath + "\\" + fileName;  
            if (!System.IO.File.Exists(fileSavePath))  
            {  
                System.IO.File.Delete(fileSavePath);  
            }  
        }  
    }  
    catch (Exception e)  
    {  
        Response.Clear();  
        Response.StatusCode = 200;  
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";  
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;  
    }  
    return Content("");  
}  
 
 
For your convenience, we have attached the sample in the below link.  
  
Kindly look at the sample and let us know whether it meets your requirement in your side and also let us know if you need further assistance on this. 

Regards, 
Ponmani M 



OL Olumuyiwa April 13, 2021 06:51 PM UTC

Thank you for your post. However, when I change the target framework from .Net 2.2 (The source code sent) to .net framework 3.1 or later

the same error occured: File failed to upload

I guess is the routing problem from startup.cs.
if  this is used
app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
 the editor will not be able to connect to the PageModel

I'm using RazorPage and not MVC

Please find the attached file. I have changed the target framework to .net 3.1

Warm Regards
Olumuyiwa

Attachment: Razorpages_74e4911f.zip


PM Ponmani Murugaiyan Syncfusion Team April 14, 2021 04:31 PM UTC

Hi Olumuyiwa, 

Thanks for the update. 

Currently we are checking the reported query. We will update further details in 2 business days. We appreciate your patience until then. 

Regards, 
Ponmani M 



KU Kuo May 1, 2022 12:26 PM UTC

hi..

I got a 400 error when i post 「Remove handler」 (however,「Save handler」 is ok).


Remove code is below:


        [AcceptVerbs("Post")]

        public IActionResult OnPostRemove(IList<IFormFile> UploadFiles)

        {

            try

            {

                foreach (var file in UploadFiles)

                {

                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                    var filePath = Path.Combine(_hostingEnvironment.WebRootPath);

                    var fileSavePath = @filePath + "\\UpdFiles\\" + fileName;

                    if (!System.IO.File.Exists(fileSavePath))

                    {

                        System.IO.File.Delete(fileSavePath);

                    }

                }

            }

            catch (Exception e)

            {

                Response.Clear();

                Response.StatusCode = 200;

                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";

                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;

            }

            return Content("");

            //return RedirectToPage("UploadFiles");

        }



cshtml file is below:@page

@using Microsoft.Net.Http.Headers

@model Razor.Pages.TestZone.UploadFilesModel


@{

    var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "UploadFiles?handler=Save", RemoveUrl = "UploadFiles?handler=Remove", ChunkSize = 3002400 };

}

@Html.AntiForgeryToken()

<ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings" autoUpload="false" uploading="addTokens" maxFileSize="3024000" allowedExtensions=".doc, .docx, .xls, .xlsx, .jpg, .jpeg, .png, .pdf" locale="tw-ZH"></ejs-uploader>


<script>

    function addTokens(args) {

        args.currentRequest.setRequestHeader('XSRF-TOKEN', document.getElementsByName('__RequestVerificationToken')[0].value);

 }

</script>













SP Sureshkumar P Syncfusion Team May 2, 2022 12:20 PM UTC

We will validate the requirement in our component. We update you in two business days (May 5th, 2022).



DR Deepak Ramakrishnan Syncfusion Team May 6, 2022 05:28 PM UTC

We are still validating your requirement , We will update the details within two business days (May 10th 2022).



SP Sureshkumar P Syncfusion Team May 10, 2022 12:11 PM UTC

Based on your provided code example, the Tokens are not set in the remove request header. So we suggest you add the same tokens
by using the BeforeRemove or OnRemove events to achieve your requirement.



KU Kuo replied to Sureshkumar P May 11, 2022 05:42 AM UTC

Hi..

Do you have any demo code that can work for me to verify delete function, thx a lots.



DR Deepak Ramakrishnan Syncfusion Team May 16, 2022 04:41 PM UTC

Hi Kuo,

Please find the attached sample as per your requirement . We have added request headers in uploading and removing event of the uploader.


[Index.cshtml]

@Html.AntiForgeryToken()

<div class="upload-wrapper">

    <ejs-uploader id="uploadFiles" asyncSettings="@asyncSettings"  multiple="false" autoUpload="true" uploading="addTokens" removing="addTokens"></ejs-uploader>

</div>

 

<script>

    function addTokens(args) {

        console.log(args)

        args.currentRequest.setRequestHeader('XSRF-TOKEN', document.getElementsByName('__RequestVerificationToken')[0].value);

    }

   

</script>



Thanks,

Deepak R.


Attachment: Razorpages_581f307c.zip


KU Kuo replied to Deepak Ramakrishnan May 18, 2022 12:06 AM UTC

thank you ...



SP Sureshkumar P Syncfusion Team May 18, 2022 11:15 AM UTC

Olumuyiwa,


Thanks for your update.


Regards,

Sureshkumar P


Loader.
Up arrow icon