How to properly retrieve a record by ID - angularjs

In my Angular/WebAPI app I'm struggling with retrieving a specific record by its id.
On the Front-End I have a controller and a data service. The controller calls a method on the data service, and the data service makes $http call to a WebAPI.
In my controller I'm passing the OID of the desired record to the getServiceRequestById method of the data service. Once of my issues is, that the actual value of that OID comes out as :1 instead of just 1.
My other issue is, that when the data service makes a call to WebAPI, the WebAPI perceives the request, as if it caries no ID in it, and passes that request onto its Get() method, instead of Get(int Id).
Here is my Front-End controller:
angular.module('frontEndApp').controller('EditServiceRequestCtrl',['$scope', 'requestsRepository','$routeParams',
function ($scope, requestsRepository,$routeParams) {
console.log("This is EditServiceRequestCtrl ; $routeParams: " + $routeParams);
//First we make a call to the data service, to fetch our ServiceRequest by its OID
//Then, in the callback function, we populate the $scope models below with the data of our retreived ServiceRequest
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
var Id = getCleanId();
//var cleanId = id.substring(0, 2);
console.log('getCleanId Id: ' + Id);
requestsRepository.getServiceRequestById(Id, function (request) {
$scope.OID = request.OID;
$scope.RequestorName = request.RequestorName;
$scope.RequestorBusinessUnit = request.RequestorBusinessUnit;
$scope.CustomerName = request.CustomerName;
$scope.CscContactPerson = request.CscContactPerson;
$scope.IsWbsCodeAvailable = request.IsWbsCodeAvailable;
$scope.SalesforceIdNumber = request.SalesforceIdNumber;
$scope.ProjectCtv = request.ProjectCtv;
$scope.RequestedCompletionDate = request.RequestedCompletionDate;
$scope.ToBeUsedForCloudMigration = request.ToBeUsedForCloudMigration;
$scope.ToBeUsedForDatacenterMove = request.ToBeUsedForDatacenterMove;
$scope.ToBeUsedForServerRefresh = request.toBeUsedForServerRefresh;
$scope.DataRequirements = request.DataRequirements;
$scope.DataProtectionRequirements = request.DataProtectionRequirements;
$scope.ProjectedDataAvailability = request.ProjectedDataAvailability;
$scope.DiscoveryLeadName = request.DiscoveryLeadName;
$scope.SelectedCountries = request.SelectedCountries;
$scope.ManualDiscovery = request.ManualDiscovery;
$scope.AutomatedDiscovery = request.AutomatedDiscovery;
$scope.DataLoadUsingMasterTemplate = request.DataLoadUsingMasterTemplate;
$scope.DataLoadUsingAutomatedInterface = request.DataLoadUsingAutomatedInterface;
$scope.DataLoaderRequiresSitizenship = request.DataLoaderRequiresSitizenship;
$scope.countries = [
{
name: "US", checked: false
},
{
name: "UK", checked: false
},
{
name: "France", checked: false
},
{
name: "Germany", checked: false
},
{
name: "Sweden", checked: false
},
{
name: "Danmark", checked: false
}
];
var list = [];
$scope.checkit = function () {
for (var p in $scope.countries) {
if ($scope.countries[p].checked) {
list.push($scope.countries[p].name);
console.log("selected country: " + $scope.countries[p].name + " " + $scope.ProjectedDataAvailability);
}
} return list;
}
console.log('EditServiceRequestCtrl $scope.RequestorName : ' + $scope.RequestorName);
});
$scope.updateServiceRequest = function () {
var ServiceRequest = {
requestorName: $scope.RequestorName,
requestorBusinessUnit: $scope.RequestorBusinessUnit,
customerName: $scope.CustomerName,
cscContactPerson: $scope.CscContactPerson,
isWbsCodeAvailable: $scope.IsWbsCodeAvailable,
salesforceIdNumber: $scope.SalesforceIdNumber,
projectCtv: $scope.ProjectCtv,
requestedCompletionDate: $scope.RequestedCompletionDate,
projectedDataAvailability: $scope.ProjectedDataAvailability,
toBeUsedForCloudMigration: $scope.ToBeUsedForCloudMigration,
toBeUsedForDatacenterMove: $scope.ToBeUsedForDatacenterMove,
toBeUsedForServerRefresh: $scope.ToBeUsedForServerRefresh,
dataRequirements: $scope.DataRequirements,
dataProtectionRequirements: $scope.DataProtectionRequirements,
selectedCountries:
list.filter(function (itm, i, a) {
return i == a.indexOf(itm);
}).toString(),
projectedDataAvailability: $scope.ProjectedDataAvailability,
discoveryLeadName: $scope.DiscoveryLeadName,
manualDiscovery: $scope.ManualDiscovery,
automatedDiscovery: $scope.AutomatedDiscovery,
dataLoadUsingMasterTemplate: $scope.DataLoadUsingMasterTemplate,
dataLoadUsingAutomatedInterface: $scope.DataLoadUsingAutomatedInterface,
dataLoaderRequiresSitizenship: $scope.DataLoaderRequiresSitizenship
};
requestsRepository.updateServiceRequest(ServiceRequest);
}
}]);
Here is my Front-End data service:
frontEndApp.factory('requestsRepository',function ($http) {
var createServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("createServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("createServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var updateServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "PUT", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("updateServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("updatetServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var getServiceRequests = function (successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
var getServiceRequestById = function (Id,successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests/' + Id
}).success(function (data, status, headers, config) {
console.log("getServiceRequestById, data: " + data);
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
return {
createServiceRequest: createServiceRequest, getServiceRequests: getServiceRequests,
updateServiceRequest: updateServiceRequest, getServiceRequestById: getServiceRequestById
};
});
And here is my Back-End WebAPI:
public HttpResponseMessage Get()
{
var requestList = from req in new XPQuery<DummyRequest>(uow) select req;
List<AccountViewServiceRequest> dataList = new List<AccountViewServiceRequest>();
foreach(var item in requestList)
{
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
dataList.Add(sr);
}
var response = Request.CreateResponse(HttpStatusCode.OK, dataList.ToList());
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
public HttpResponseMessage Get(int Oid)
{
var item = (from req in new XPQuery<DummyRequest>(uow) where req.Oid == Convert.ToInt32(Oid) select req).First();
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
var response = Request.CreateResponse(HttpStatusCode.OK, sr);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
Which part should I correct to successfully retrieve a single e record based on its OID?

Since it appears that your first issue is related to this routine:
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
Change the substring starting position to 1 to remove the prepended colon.
var getCleanId = function () {
return $routeParams.OID.substring(1, 2)
};
That in turn should fix the issue with not getting a single record out of the web api. The web api is trying to find a matching function signature in the controller on the web server. The only parameter can't convert to an integer, so it uses the Get() instead of the Get(int Oid).

Related

Store and retrieve correct data

I want to create a form for selecting a number of receiving then that's the reference items store correctly and retrieve correctly.
this is my angular js code
$scope.addreciveditemtemp = function(receiving,newreciveditemtemp) {
$scope.receiving_item = [ ];
$http.get('api/reciveditem').success(function(response) {
$scope.receiving_item = response;
for (var i=0;i<$scope.receiving_item.length;i++){
var receiving_item = $scope.receiving_item[i];
if(receiving_item.receiving_id===receiving.id){
console.log(receiving_item);
$http.post('api/reciveditemtemp', {
recived_id: receiving_item.receiving_id,
item_id: receiving_item.item_id,
cost_price: receiving_item.cost_price,
prequantity: receiving_item.quantity,
pretotal_cost: receiving_item.total_cost,
realtotal: receiving_item.total_cost
}).success(function(data, status, headers, config) {
$scope.reciveditemtemp.push(data);
$http.get('api/reciveditemtemp').success(function(data) {
$scope.reciveditemtemp = data;
});
});
}
}
});
};
this is my laravel controller code
public function store()
{ $this->newItem();
}
public function newItem()
{
$receiving_item = ReceivingItem::where('receiving_id', Input::get('item_id'))->get();
foreach($receiving_item as $value)
{
$reciveditemtemps = new reciveditemtemp;
$reciveditemtemps->recived_id = $value->receiving_id;
$reciveditemtemps->item_id = $value->item_id;
$reciveditemtemps->cost_price = $value->cost_price;
$reciveditemtemps->prequantity = $value->quantity;
$reciveditemtemps->pretotal_cost = $value->total_cost;
$reciveditemtemps->realquantity = $value->quantity;
$reciveditemtemps->realtotal = $value->cost_price * $value->realquantity;
$reciveditemtemps->save();
//return $ReceivingTemps;
}
return $reciveditemtemps;
}
But console answer is correct
how to solve this problem?? please help me.
This looks sketchy:
ERRONEOUS
}).success(function(data, status, headers, config) {
$scope.reciveditemtemp.push(data);
$http.get('api/reciveditemtemp').success(function(data) {
$scope.reciveditemtemp = data;
});
});
To push a value to an array and then replace the entire array does not seem right.
change the controller code.
public function newItem()
{
$reciveditemtemps = new reciveditemtemp;
$reciveditemtemps->recived_id = Input::get('receiving_id');
$reciveditemtemps->item_id = Input::get('item_id');
$reciveditemtemps->cost_price = Input::get('cost_price');
$reciveditemtemps->prequantity = Input::get('prequantity');
$reciveditemtemps->pretotal_cost = Input::get('pretotal_cost');
$reciveditemtemps->realtotal = Input::get('realtotal');
$reciveditemtemps->realquantity = Input::get('prequantity');
$reciveditemtemps->save();
return $reciveditemtemps;
}

Passing params: to Web API works with $http.get but not $http.Post

AngularJS 1.59
This API call works with $http.get.
JS ViewModel
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiGet('api/order/create', { params: { order: orderJSON } },
function (result) {
var orderId = result.data;
});
}
App.js
self.apiGet = function (uri, data, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.get(AlbumApp.rootPath + uri, data)
.then(function (result) {
success(result);
if (always != null)
always();
self.isLoading = false;
}, function (result) {
if (failure == null) {
if (result.status != 400)
self.modelErrors = [result.status + ': ' + result.statusText +
' - ' + result.data];
else
self.modelErrors = [result.data + ''];
self.modelIsValid = false;
}
else
failure(result);
if (always != null)
always();
self.isLoading = false;
});
}
self.apiPost = function (uri, data, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.post(AlbumApp.rootPath + uri, data)
.then(function (result) {
success(result);
if (always != null)
always();
self.isLoading = false;
}, function (result) {
if (failure == null) {
if (result.status != 400)
self.modelErrors = [result.status + ': ' + result.statusText + ' - ' + result.data];
else self.modelErrors = [result.data];
self.modelIsValid = false;
}
else failure(result);
if (always != null) always();
self.isLoading = false;
});
}
APIController
[HttpGet]
[Route("create")]
public IHttpActionResult Create(string order) {
var _order = JsonConvert.DeserializeObject<Order>(order); ... }
But since this is a Create function I want to use $http.post. When I change the call to
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiPost('api/order/create', { params: { order: orderJSON } },
//null,
function (result) {
var orderId = result.data;
});
}
and my controller Action to
[HttpPost]
[Route("create")]
public IHttpActionResult Create(string order) {
var _order = JsonConvert.DeserializeObject<Order>(order); ... }
I get a 404 error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:50597/api/order/create'.
</Message>
<MessageDetail>
No action was found on the controller 'OrderApi' that matches the request.
</MessageDetail>
</Error>
Is this a bug or am I missing some conceptual point or do I have an error in my code?
Solution: (Thank you Giovani)
params: needs to be passed to the config in the $http.get and $http.post. The two methods have different signatures.
In apiGet renamed data to config.
In apiPost added a config.
In apiPost call added a null so the params: is passed to config rather than data.
App.js
self.apiGet = function (uri, config, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.get(AlbumApp.rootPath + uri, config)
...
self.apiPost = function (uri, data, config, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.post(AlbumApp.rootPath + uri, data, config)
JS ViewModel
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiPost('api/order/create', null, { params: { order: orderJSON } },
function (result) {
var orderId = result.data;
}); }
$http.get() and $http.post() have a different method signature. more info
$http.get(<URL>, <DATA (params, responseType, etc..)>)
$http.post(<URL>, <BODY_DATA>, <DATA (params, responseType, etc..)>

Inserting new record from AngularJS using Web API

Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.
First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles
Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:
$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
ArticlesController.cs:
[HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
DataLayer.cs:
public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
I hope someone could help me fix these. Thankie so much!

Django upload error: Upload a valid image

I am looking for the easiest way to post image via angular and django rest.
I've took some code samples and combined to this, but I am still getting error:
Upload a valid image. The file you uploaded was either not an image or a corrupted image.
Maybe someone has a good eye and could easily see what I am missing here?
P.S.
libjpeg-dev is already the newest version
javascript.js
/* global angular */
var products = angular.module('products',['ngCookies']);
products.config(function($interpolateProvider) {
//allow django templates and angular to co-exist
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
products.run(function($rootScope, $log, $http, $cookies) {
$http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});
products.factory('ModelUtils', function($http, $log) {
var handleErrors = function(serverResponse, status, errorDestination) {
if (angular.isDefined(errorDestination)) {
if (status >= 500) {
errorDestination.form = 'Server Error: ' + status;
} else if (status >= 401) {
errorDestination.form = 'Unauthorized Error: ' + status;
} else {
angular.forEach(serverResponse, function(value, key) {
if (key != '__all__') {
errorDestination[key] = angular.isArray(value) ? value.join("<br/>") : value;
} else {
errorDestination.form = errorDestination.form || '' + key + ':' + angular.isArray(value) ? value.join("<br/>") : value;
}
});
}
}
};
var ModelUtils = {
get: function(url,id) {
$http.get(url + id + '/').then(function(response){response.data});
},
create: function(url, obj, errors) {
//TODO
//obj.author = username;
return $http.post(url, obj).
success(function(response, status, headers, config) {
angular.extend(obj, response);
}).
error(function(response, status, headers, config) {
handleErrors(response, status, errors);
});
},
save: function(url, obj, errors) {
if (angular.isDefined(obj.id)) {
return $http.put(url + obj.id + '/', obj).
success(function(response, status, headers, config) {
angular.extend(obj, response);
});
error(function(response, status, headers, config) {
handleErrors(response, status, errors);
});
} else {
return this.create(url, obj, errors);
}
},
del: function(url, obj) {
console.log(url, obj, obj.id);
return $http.delete(url + obj.id + '/');
}
};
return ModelUtils;
});
products.controller('ListCtrl', function ListCtrl($scope, $log, $http, ModelUtils) {
// dcl variables
$scope.tempUrlJs = document.getElementById("tempVar1").value;
// just a dummy init function
$scope.initialize = function(data) {
$log.log('initialize',data);
$scope.initData = data;
};
$scope.loaditems = function() {
console.log('hello');
$scope.items = $http.get('/api/images/').then(function(response){
return response.data;
});
};
//mainFlow
$scope.loaditems($scope.tempUrlJs);
$scope.currentitem = {};
$scope.errors = {};
console.log('hello');
$scope.saveitem = function() {
console.log('hello');
ModelUtils.save('/api/images/',$scope.currentitem, $scope.errors).then(function(){
$scope.loaditems();
$scope.currentitem = {};
});
};
$scope.delitem = function(item) {
console.log('0');
ModelUtils.del('/api/images/',item).then(function(){
console.log('10');
$scope.loaditems();
});
};
});
products.controller('subListCtrl', function ListCtrl($scope, $log, $http, ModelUtils) {
// dcl variables
$scope.tempUrlJs = '/api/ingredients/'
//document.getElementById("tempVar2").value;
// just a dummy init function
$scope.initialize = function(data) {
$log.log('initialize',data);
$scope.initData = data;
};
$scope.loaditems = function(tempUrlJs) {
$scope.items = $http.get(tempUrlJs).then(function(response){
return response.data;
});
};
$scope.saveitem = function() {
ModelUtils.save('/api/ingredients/',$scope.currentitem, $scope.errors).then(function(){
$scope.loaditems();
$scope.currentitem = {};
});
};
//mainFlow
$scope.loaditems($scope.tempUrlJs);
$scope.currentitem = {};
$scope.errors = {};
});
index.html
<body ng-app="products">
<div ng-controller="ListCtrl">
<h3>Insert image</h3>
<form>
<ul>
<li>Title: <input type="text" name="title" ng-model="currentitem.title"/><span class="error">{[{ errors.title }]}</span></li>
<li>Description: <input type="text" name="description" ng-model="currentitem.description"/><span class="error">{[{ errors.description }]}</span></li>
<li>Image: <input type="file" name="image" ngf-select ng-model ="currentitem.image" accept="image/*"/><span class="error">{[{ errors.image }]}</span></li>
</ul>
<button ng-click="saveitem()">Save</button>
<pre>currentitem:{[{ currentitem | json }]}</pre>
</form>
serializers.py
class Base64ImageField(serializers.ImageField):
def to_internal_value(self, data):
from django.core.files.base import ContentFile
import base64
import six
import uuid
def decode_base64(data):
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'='* (4 - missing_padding)
return base64.decodestring(data)
if isinstance(data, six.string_types):
if 'data:' in data and ';base64,' in data:
header, data = data.split(';base64,')
try:
data = decode_base64(data)
decoded_file = base64.b64decode(data)
#decoded_file = decode_base64(decoded_file)
except TypeError:
self.fail('invalid_image')
file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough
file_extension = self.get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
data = ContentFile(decoded_file, name=complete_file_name)
return super(Base64ImageField, self).to_internal_value(data)
def get_file_extension(self, file_name, decoded_file):
import imghdr
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
class UploadedImageSerializer(serializers.ModelSerializer):
image = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = image
fields = ('pk', 'image', 'thumbnail', 'title', 'description', )
read_only_fields = ('thumbnail',)
views.py
class UploadedImages(TemplateView):
template_name = 'image.html'
queryset = image.objects.all()
serializer_class = UploadedImageSerializer
class UploadedImagesApi(generics.ListCreateAPIView):
queryset = image.objects.all()
model = image
serializer_class = UploadedImageSerializer
models.py
def scramble_uploaded_filename(instance, filename):
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension)
def create_thumbnail(input_image, thumbnail_size=(256, 256)):
if not input_image or input_image == "":
return
image = Image.open(input_image)
image.thumbnail(thumbnail_size, Image.ANTIALIAS)
filename = scramble_uploaded_filename(None, os.path.basename(input_image.name))
arrdata = filename.split(".")
extension = arrdata.pop()
basename = "".join(arrdata)
new_filename = basename + "_thumb." + extension
image.save(os.path.join(settings.MEDIA_ROOT, new_filename))
return new_filename
class image(models.Model):
image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename)
thumbnail = models.ImageField("Thumbnail of uploaded image", blank=True)
title = models.CharField("Title of the uploaded image", max_length=255, default="Unknown Picture")
description = models.TextField("Description of the uploaded image", default="")
def __str__(self):
return self.title
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
self.thumbnail = create_thumbnail(self.image)
super(image, self).save(force_update=force_update)
I don't know angular so this might be completely wrong, but don't you always need enctype="multipart/form-data" in your <form> tag to upload images?

AngularJs, FileSaver Export To Excel with Turkish Chars?

I can export to Excel with FileSaver in my solution. Here my sources:
tapuController.cs:
[Route("Tapu/tcKimlikNoIleToEcel")]
public void tcKimlikNoIleToEcel(string tcKimlikNo)
{
List<TapuZeminModel> zeminler = new List<TapuZeminModel>();
zeminler = TapuModule.GetZeminListFromTcNo(tcKimlikNo);
List<TapuZeminViewModel> zeminList = new List<TapuZeminViewModel>();
foreach (var zemin in zeminler)
{
foreach (var hisse in zemin.Hisseler)
{
TapuZeminViewModel ze = new TapuZeminViewModel();
ze.Ad = hisse.Kisi.Ad;
ze.AdaNo = zemin.AdaNo;
if (zemin.KatMulkiyeti != null)
{
ze.ArsaPay = zemin.KatMulkiyeti.ArsaPay;
ze.ArsaPayda = zemin.KatMulkiyeti.ArsaPayda;
ze.BagimsizBolumNo = zemin.KatMulkiyeti.BagimsizBolumNo;
ze.Blok = zemin.KatMulkiyeti.Blok;
ze.Giris = zemin.KatMulkiyeti.Giris;
}
ze.Cilt = zemin.CiltNo;
ze.EdinmeSebep = hisse.EdinmeSebep;
ze.HisseId = hisse.TapuKod;
ze.HissePay = hisse.HissePay;
ze.HissePayda = hisse.HissePayda;
ze.Il = zemin.Il.Ad;
ze.Ilce = zemin.Ilce.Ad;
ze.KisiId = hisse.Kisi.TapuKod;
ze.ParselNo = zemin.ParselNo;
ze.Sayfa = zemin.SayfaNo;
ze.Kurum = zemin.Kurum.Ad;
ze.ZeminId = zemin.TapuKod;
ze.ZeminTip = zemin.ZeminTip.Ad;
ze.Mahalle = zemin.Mahalle.Ad;
ze.Nitelik = zemin.AnaTasinmaz.Nitelik;
ze.Mevkii = zemin.AnaTasinmaz.Mevkii;
if (hisse.Kisi.GercekKisi != null)
{
ze.SoyAd = hisse.Kisi.GercekKisi.SoyAd;
ze.TcKimlikNo = hisse.Kisi.GercekKisi.TcKimlikNo;
}
if (hisse.Kisi.TuzelKisi != null)
{
ze.TuzelKisiAd = hisse.Kisi.TuzelKisi.Ad;
ze.VergiNo = hisse.Kisi.TuzelKisi.VergiNo;
ze.SicilNo = hisse.Kisi.TuzelKisi.SicilNo;
}
zeminList.Add(ze);
}
}
StringBuilder dosyaAdi = new StringBuilder();
dosyaAdi.Append(DateTime.Now.ToString("dd.MM.yyyy HH.mm"));
dosyaAdi.Append("-" + tcKimlikNo);
dosyaAdi.Append(".xls");
GridView gv = new GridView();
gv.DataSource = zeminList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + dosyaAdi.ToString());
Response.ContentType = "application/ms-excel=utf-8";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
tapuControllerService.js:
angular.module('TapuAppModule')
.factory('TapuControllerService', function TapuIlApiFactory($http) {
return {
adaParselSorguToExcel: function (zeminArg) {
return $http({ method: "GET", url: "Tapu/ExportToExcel", params: { ada: zeminArg.Ada, ilceId: zeminArg.IlceId, mahId: zeminArg.MahalleId, parsel: zeminArg.Parsel } });
},
tcKimlikNoIleToEcel: function (manuelTcKimlikNo) {
return $http({ method: "GET", url: "Tapu/tcKimlikNoIleToEcel", params: { tcKimlikNo: manuelTcKimlikNo } });
},
kurumIdIleToEcel: function (manuelKurumId) {
return $http({ method: "GET", url: "Tapu/kurumIdIleToEcel", params: { kurumId: manuelKurumId } });
}
}
});
tapuController.js:
$scope.exportToExcel = function () {
$scope.ZeminArg = {
Ada: $scope.selectedAdaNo,
Parsel: $scope.selectedParselNo,
MahalleId: $scope.selectedMahalle,
IlceId: $scope.selectedIlce
};
if (document.getElementById('adaparsel').className == "tab-pane fade active in") {
var fileName = "MahalleId-" + $scope.ZeminArg.MahalleId + "_IlceId-" + $scope.ZeminArg.IlceId + "_AdaNo-" + $scope.ZeminArg.Ada + "_ParselNo-" + $scope.ZeminArg.Parsel;
TapuControllerService.adaParselSorguToExcel($scope.ZeminArg)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("tckimlikno").className == "tab-pane fade active in") {
var fileName = "TcNo-" + $scope.manuelTcKimlikNo;
TapuControllerService.tcKimlikNoIleToEcel($scope.manuelTcKimlikNo)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
if (document.getElementById("kurum").className == "tab-pane fade active in") {
var fileName = "kurum-" + $scope.manuelKurumId;
TapuControllerService.kurumIdIleToEcel($scope.manuelKurumId)
.success(function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
saveAs(blob, datetime + '-' + fileName + '.xls');
}).error(function () {
//Some error log
});
}
};
And i'm using FileSaver. Here filesaver Url
Everything is ok. It's working. But i can't use Turkish chars. I tried some encoding but not worked. Here is my error's pic:
For example first SoyAd is : FERİKOĞLU
Second row Ad is : ALATTİN
etc. What should i do for output Excel with Turkish Chars??

Resources