Uploading files with angualrjs and abp templates with webapi

I am using ABP (ASP.NET Boilerplate) Web API and angularjs to create a SinglePageApplication. I've already worked on server side method calling with angular and abp framework. It's easy to just send JSON data, but I have no idea how to send files.

Here is an example of sending JSON-Data:
<B> 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?

+3


source to share


2 answers


For your frontend please take a look at this link: https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

For your back service, I think this link will give you the right idea: https://msdn.microsoft.com/en-us/library/ms227669(v=vs.140).aspx



Hope this helps you, good luck :)

0


source


Nice way to upload a file:

  • Create a controller named UploadController from the AbpController base

  • Add a file upload method. 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 client submission, post 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 the download is complete, get the result using a callback
  vm.productPhotoUploaded = function (response) {
                if (!response.success) {
                    return;
                }

                vm.productPhotoFileName = response.fileName;
            };

      

  1. At this point, you have a unique file name generated on the server for this file. You can now update your client object. Or, you can use your cascading savings.

Note. One drawback of this approach is that when the user uploads the file and then cancels the save of the main object, you need to manually process to delete the temp file uploaded to the server.

0


source







All Articles