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?
A good way of achieving upload file:
Create a controller named UploadController from the base AbpController
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 }); } }
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(); };
vm.productPhotoUploaded = function (response) { if (!response.success) { return; } vm.productPhotoFileName = response.fileName; };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With