Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading files using angualrjs and abp boilerplate with webapi

I am using ABP (ASP.NET Boilerplate) Web API and angularjs to build a SinglePageApplication. I already got it working to call the server side methods via angular and the abp framework. It is easy to just send JSON-data but I have no idea how to send files.

Here is an example of sending JSON-Data:
Server-Code

public class PostAppService : ApplicationService, IPostAppService
{
    public LoginOutput Login(LoginInput input)
    {
        doSomeStuffHere();
    }
}

[DependsOn(typeof(AbpWebApiModule))]
public class SimpleTaskSystemWebApiModule : AbpModule
{
    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

        DynamicApiControllerBuilder
            .ForAll<IApplicationService>(Assembly.GetAssembly(typeof(SimpleTaskSystemApplicationModule)), "tasksystem")
            .Build();
    }
}

Client-Code

(function() {
    var app = angular.module('app');

    var controllerId = 'sts.views.authentication.login';
    app.controller(controllerId, [
        '$scope', '$location', 'abp.services.tasksystem.authentication',
        function ($scope, $location, authService) {
            var vm = this;

            vm.user = {
                username: '',
                password: ''
            };

            var localize = abp.localization.getSource('SimpleTaskSystem');

            vm.login = function () {
                abp.ui.setBusy(
                    null,
                    authService.login(
                        vm.user
                    ).success(function(response) {
                        displayLoggedInMessage();
                    })
                );
            };
        }
    ]);
})();

I would like to do something like this but instead of sending JSON-Data I would like to send an image selected via:

<input type="file"/>

Any ideas?

like image 851
Young Socke Avatar asked Nov 21 '25 04:11

Young Socke


1 Answers

A good way of achieving upload file:

  1. Create a controller named UploadController from the base AbpController

  2. Add a method to upload the file. Let's name it ProductPhoto

public JsonResult ProductPhoto(string comment, int productId)
        {
            try
            {
                if (!Request.Files.Any() || Request.Files[0] == null)
                {
                    return null;
                }

                var fileName = Guid.NewGuid();
                var uniqueFilePath = @"~\Upload\ProductPhotos\" + fileName;
                Request.Files[0].SaveAs(uniqueFilePath);
                 
                //save your additional parameters such as comment, productId
                return Json(new
                {
                    Success = true,
                    FileName = fileName
                });
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString);
                return Json(new
                {
                    Success = false
                });
            }
        }
  1. On the client send send the file using jquery or angular
vm.showProductPhotoUploadFileDialog = function () {
                var formData = = new FormData()
                formData .append("productId", vm.form.product.id);
                formData .append("formId", vm.form.id);
                if (vm.newProductPhoto.comment) {
                    formData .append("comment", vm.newProductPhoto.comment);
                }

                $('#productPhotoFileInput').click();
            };
  1. After upload completes get the result using callback
  vm.productPhotoUploaded = function (response) {
                if (!response.success) {
                    return;
                }

                vm.productPhotoFileName = response.fileName;
            };
  1. At this step you have the unique filename generated on the server for this file. Now you can update your client side object. Or you can go on your cascade savings.

Note: One disadvantage of this approach is; when user uploads file and then cancels the master entity save, you have to manually handle to delete the temp file uploaded to server.

like image 148
Alper Ebicoglu Avatar answered Nov 22 '25 19:11

Alper Ebicoglu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!