Base solution for your next web application
Open Closed

Maui Document Upload Error #12501


User avatar
0
stanley5389 created

I have added simple file upload in empty project 14.2.1 file upload error

@using CoreSync.Maui.Services.Navigation

@inherits CoreSyncMainLayoutPageComponentBase @attribute [Route("/" + NavigationUrlConsts.DocumentManagers_Create_Or_Edit + "/{DocumentManagerId:int?}")]

<div class="container"> <EditForm Model="CreateOrEditDocumentManagerModel" OnValidSubmit="@Save"> <DataAnnotationsValidator/> <div class="card mb-3"> <div class="card-body">

                    &lt;div class=&quot;d-flex flex-column mb-4&quot;&gt;
                        &lt;label class=&quot;form-label fw-semibold&quot;&gt;
                            @L("File")
                        &lt;/label&gt;
                        &lt;InputFile OnChange=&quot;@(e =&gt; OnFileSelected(e, "File"))" class="form-control" />
                        @if (FileDetailsDictionary.TryGetValue("File", out var file) && file != null)
                        {
                            &lt;div class=&quot;mt-2 text-success&quot;&gt;@file.FileName&lt;/div&gt;
                        }
                    &lt;/div&gt;
                &lt;div class=&quot;d-flex flex-column mb-4&quot;&gt;
            &lt;label class=&quot;form-label fw-semibold&quot;&gt;
                &lt;span class=&quot;required&quot;&gt;
                    @L("Name")
                &lt;/span&gt;
            &lt;/label&gt;
            &lt;InputText @bind-Value=&quot;CreateOrEditDocumentManagerModel.Name&quot; class=&quot;form-control form-control-solid&quot;/&gt;
            &lt;ValidationMessage For=&quot;@(() =&gt; CreateOrEditDocumentManagerModel.Name)"/>
        &lt;/div&gt;
        
            &lt;div class=&quot;text-center&quot;&gt;
                @if (_hasEditPermission || _hasCreatePermission)
                {
                    &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary w-100&quot;&gt;
                        &lt;span class=&quot;indicator-label&quot;&gt;@L("Save")&lt;/span&gt;
                    &lt;/button&gt;
                }
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/EditForm&gt;
&lt;div class=&quot;card&quot;&gt;
    &lt;div class=&quot;card-body&quot;&gt;
        @if (CreateOrEditDocumentManagerModel.IsEditMode && _hasDeletePermission)
        {
            &lt;button type=&quot;button&quot; class=&quot;btn btn-danger w-100&quot; @onclick=&quot;Delete&quot;&gt;@L("Delete")&lt;/button&gt;
        }
    &lt;/div&gt;
&lt;/div&gt;

</div>

using Abp.Application.Services.Dto; using CoreSync.Authorization; using CoreSync.Maui.Core.Components; using CoreSync.Maui.Core.Threading; using CoreSync.Maui.Models.DocumentService; using CoreSync.Maui.Services.Navigation; using CoreSync.DocumentService; using Microsoft.AspNetCore.Components; using CoreSync.Maui.Services.Permission; using CoreSync.Storage; using Microsoft.AspNetCore.Components.Forms;

namespace CoreSync.Maui.Pages.DocumentService;

public partial class CreateOrEditDocumentManager : CoreSyncMainLayoutPageComponentBase { [Parameter] public int? DocumentManagerId { get; set; }

private Dictionary&lt;string, FileDetails&gt; FileDetailsDictionary = new Dictionary&lt;string, FileDetails&gt;();

private readonly ProxyDocumentManagersControllerService ProxyDocumentManagersControllerService;

private readonly bool _hasCreatePermission;

private readonly bool _hasEditPermission;

private readonly bool _hasDeletePermission;

private IDocumentManagersAppService DocumentManagersAppService { get; }

public CreateOrEditDocumentManagerModel CreateOrEditDocumentManagerModel { get; set; } = new()
{

};

public CreateOrEditDocumentManager()
{
    DocumentManagersAppService = Resolve&lt;IDocumentManagersAppService&gt;();
    _hasCreatePermission = PermissionService.HasPermission(AppPermissions.Pages_DocumentManagers_Create);
    _hasEditPermission = PermissionService.HasPermission(AppPermissions.Pages_DocumentManagers_Edit);
    _hasDeletePermission = PermissionService.HasPermission(AppPermissions.Pages_DocumentManagers_Delete);
    ProxyDocumentManagersControllerService = Resolve&lt;ProxyDocumentManagersControllerService&gt;();
}

protected override async Task OnInitializedAsync()
{
    if (DocumentManagerId.HasValue)
    {
        await SetBusyAsync(async () =>
        {
            await WebRequestExecuter.Execute(
                async () => await DocumentManagersAppService.GetDocumentManagerForEdit(new EntityDto { Id = DocumentManagerId!.Value }),
                (getDocumentManagerForEditOutput) =>
                {
                    CreateOrEditDocumentManagerModel = ObjectMapper.Map&lt;CreateOrEditDocumentManagerModel&gt;(getDocumentManagerForEditOutput.DocumentManager);
                    FileDetailsDictionary["File"] = new FileDetails
                    {
                        FileName = getDocumentManagerForEditOutput.FileFileName,
                        FileToken = getDocumentManagerForEditOutput.DocumentManager.FileToken
                    };

                    return Task.CompletedTask;
                }
            );
        });
    }

    var title = CreateOrEditDocumentManagerModel.IsEditMode ? L("EditDocumentManager") : L("CreateNewDocumentManager");

    await SetPageHeader(title);
}

private async Task Save()
{
    await SetBusyAsync(async () =>
    {
        CreateOrEditDocumentManagerModel.FileToken = FileDetailsDictionary["File"].FileToken;
        await WebRequestExecuter.Execute(
            async () => await DocumentManagersAppService.CreateOrEdit(CreateOrEditDocumentManagerModel),
            async () =>
            {
                NavigationService.NavigateTo(NavigationUrlConsts.DocumentManagers);
                await UserDialogsService.AlertSuccess(L("SuccessfullySaved"));
            }
        );
    });
}

private async Task Delete()
{
    var input = new EntityDto { Id = CreateOrEditDocumentManagerModel.Id!.Value };

    var confirm = await UserDialogsService.Confirm(L("AreYouSure"));

    if (confirm)
    {
        await SetBusyAsync(async () =>
        {
            await WebRequestExecuter.Execute(
                async () => await DocumentManagersAppService.Delete(input),
                async () =>
                {
                    await UserDialogsService.AlertSuccess(L("SuccessfullyDeleted"));
                    NavigationService.NavigateTo(NavigationUrlConsts.DocumentManagers);
                }
            );
        });
    }
}

private async Task OnFileSelected(InputFileChangeEventArgs e, string propertyName)
{
    var file = e.File;
    if (file == null)
        return;

    using var originalStream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
    using var memoryStream = new MemoryStream();
    await originalStream.CopyToAsync(memoryStream);
    memoryStream.Position = 0;

    await SetBusyAsync(async () =>
    {
        FileUploadCacheOutput result = null;

        await WebRequestExecuter.Execute(
            async () =>
            {
                result = await ProxyDocumentManagersControllerService.UploadFile(memoryStream, file.Name);
            },
            async () =>
            {
                if (result != null && string.IsNullOrEmpty(result.Message))
                {
                    FileDetailsDictionary[propertyName] = new FileDetails
                    {
                        FileToken = result.FileToken,
                        FileName = file.Name
                    };
                }
                else
                {
                    await UserDialogsService.AlertError(L(result?.Message ?? "Upload failed"));
                }
            }
        );
    });
}

}

Markdown is supported
Copy & paste or drag & drop images (max 30 MB per image)

14 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    Thank you for your feedback. I will check the situation as soon as possible and get back to you with a solution.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    I tried to reproduce this issue in the version you mentioned as well as in the latest version of Power Tools, but I wasn’t able to encounter any problems. In order to reproduce the issue accurately, could you please share the JSON file of the entity you’re having trouble with under the AspNetZeroRadTool folder? Thank you.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    { "IsRegenerate": false, "MenuPosition": "main", "RelativeNamespace": "DocumentService", "EntityName": "DocumentManager", "EntityNamePlural": "DocumentManagers", "TableName": "DocumentManagers", "PrimaryKeyType": "int", "BaseClass": "Entity", "EntityHistory": true, "AutoMigration": true, "UpdateDatabase": true, "CreateUserInterface": true, "CreateViewOnly": true, "CreateExcelExport": true, "CreateExcelImport": true, "IsNonModalCRUDPage": false, "IsMasterDetailPage": false, "GenerateOverridableEntity": false, "GenerateUnitTest": true, "GenerateUiTest": true, "GenerateMobile": true, "CreateMauiView": true, "PagePermission": { "Host": true, "Tenant": true }, "Properties": [ { "Name": "File", "Type": "file", "MaxLength": 0, "MinLength": 0, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": false, "Nullable": true, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} }, { "Name": "Name", "Type": "string", "MaxLength": -1, "MinLength": -1, "Range": { "IsRangeSet": false, "MinimumValue": 0.0, "MaximumValue": 0.0 }, "Required": false, "Nullable": false, "Regex": "", "IsMultiLingual": false, "UserInterface": { "AdvancedFilter": true, "List": true, "ListMaui": true, "CreateOrUpdate": true }, "ViewType": null, "AdditionalData": {} } ], "NavigationProperties": [], "NavigationPropertyOneToManyTables": [], "EnumDefinitions": [], "DbContext": null }

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    The Result Coming Null.

    Below all fine

    ProxyDocumentCentersControllerService public async Task<FileUploadCacheOutput> UploadFile(Stream stream, string fileName) { return await ApiClient.PostMultipartAsync<FileUploadCacheOutput>( "app/" + "DocumentCenters/" + nameof(UploadFile), stream, fileName ); }

    AbpApiClient public async Task<T> PostMultipartAsync<T>(string endpoint, Stream stream, string fileName, bool stripAjaxResponseWrapper = true) { var httpResponse = GetClient(_accessTokenManager.GetAccessToken()) .Request(endpoint) .PostMultipartAsync(multiPartContent => multiPartContent.AddFile("file", stream, fileName)); return await ValidateAbpResponse<T>(httpResponse, stripAjaxResponseWrapper); }

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    We generated an entity using the JSON file you shared with us, and when we try to upload an image on the MAUI side, the image upload process is successfully completed. At this point, we kindly ask you to debug the UploadFile method inside the DocumentManagersController class using breakpoints to identify exactly where the issue occurs. Please check if the uploaded image is being successfully set in the TempFileCache.

    Additionally, on the MAUI side, you can put a breakpoint inside the catch block of the ValidateAbpResponse method under the AbpApiClient class to see if any error is being caught. This section usually provides a more detailed error message.

    After reviewing these points, if you encounter any specific issues, please don’t hesitate to share them with us. That way, we can assist you more effectively.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    The Error like this? It is not Hitting controller

    {Flurl.Http.FlurlHttpException: Call failed with status code 404 (Not Found): POST https://10.0.2.2:44301/app/DocumentManagers/UploadFile at Flurl.Http.FlurlClient.HandleExceptionAsync(FlurlCall call, Exception ex, CancellationToken token) at Flurl.Http.FlurlClient.SendAsync(IFlurlRequest request, HttpCompletionOption completionOption, CancellationToken cancellationToken) at Flurl.Http.FlurlClient.SendAsync(IFlurlRequest request, HttpCompletionOption completionOption, CancellationToken cancellationToken) at Flurl.Http.ResponseExtensions.<ReceiveJson>d__01[[Abp.Web.Models.AjaxResponse1[[CoreSync.Storage.FileUploadCacheOutput, CoreSync.Application.Shared, Version=14.2.0.0, Culture=neutral, PublicKeyToken=null]], Abp.Web.Common, Version=10.2.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() at CoreSync.ApiClient.AbpApiClient.<ValidateAbpResponse>d__51`1[[CoreSync.Storage.FileUploadCacheOutput, CoreSync.Application.Shared, Version=14.2.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() in D:\ASPNETZERO\CoreSync\aspnet-core\src\CoreSync.Application.Client\ApiClient\AbpApiClient.cs:line 378}

    namespace CoreSync.ApiClient;

    public static class DebugServerIpAddresses { /* If you are using Genymotion Emulator, set DebugServerIpAddresses.Current = "10.0.3.2". If you are using a real Android device, set it as your computer's local IP and make sure your Android device and your computer is connecting to the internet via your local Wi-Fi. */ public static string Current = "10.0.2.2"; }

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    If your project's UI type is MVC, you need to run the Mvc project when selecting the mobile profile. If the UI type is Angular, you should run the Host project with the mobile profile. Alternatively, you can use your device's physical IPv4 address as DebugServerIpAddresses.Current.

    Related Document

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    How to create the mobile profile? Not showing on my project. https://docs.aspnetzero.com/aspnet-core-mvc/latest/Development-Guide-MAUI

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    You need to open the YourProjectName.Web.sln solution file and run the backend by selecting the Mobile profile. Alternatively, you can set the Host project as the startup project and run it with the Mobile profile. After starting the backend, you can also run the MAUI project on the emulator.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    I have done same like above. Still same error. If you want I can share my source code

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    You can send your project to [email protected] so we can suggest a more accurate solution. Thank you.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Hi, I have shared. Get back me ASAP. Thanks.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    stanley5389 created

    Hi, Any update? I will not get any response from Email!

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @stanley5389

    To fix the file upload error, please make the following change:

    You need to add the [Area("App")] attribute to your controller. For example:

    [Area("App")]
    [AbpMvcAuthorize(AppPermissions.Pages_Developers)]
    public class DevelopersController : ExcelImportControllerBase
    {
        // ...
    }
    

    This ensures that the routing system can correctly locate your controller. In ASP.NET Zero (v14.2.1), the default area is App, so if you don't specify it, you might get a 404 Not Found error.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)