I am struggling converting image to byte array using client side script. I have to convert image to byte array, and pass this array to web service , so that the web services can save the image in server. Any one please help me.
$scope.file=function(user){
//console.log("hhhhh",angular.toJson($scope.user));
console.log(ContextService.object);
$scope.users=ContextService.object;
console.log($scope.user);
//$scope.file=$scope.file;
console.log($scope.user.file);
var file=$scope.user.file;
var bytes = [];
var fileReader = new FileReader();
fileReader.onload = function (e) {
var naveen=fileReader.result;
for (var i = 0; i < naveen.length; ++i)
{
bytes.push(naveen.charCodeAt(i));
bytes.push(0);
}
console.log("bytes",bytes);
$scope.call(bytes);
};
fileReader.onerror = function(err) {
console.log(err);
};
fileReader.readAsBinaryString(file);
$scope.call=function(bytes)
{
$scope.image=bytes;
}
$timeout(function() {
console.log("vvvvv",$scope.image);
$scope.users.file=$scope.image;
console.log("dsfdsfds",$scope.users);
var url = "http://127.0.0.1:8080/api/signup";
$http({
method : "POST",
url : url,
data :angular.toJson($scope.users),
headers : {
"content-type" : "application/json",
"Accept" : "application/json"
}
})
.success(function(data) {
console.log("Detail", angular.toJson(data));
$state.go("login");
});
}, 3000);
Related
I have an array of colors and sizes, and some other data like product_name and images, I am able to send image files and product_name but when I attach color_and_sizes array then it says 500 error
Here is my Code :(Angularjs and Laravel Controller )
Basically I want to save all the details in the database but I am unable to save the color and sizez details.
$scope.admin_add_product=function(){
var product_name=$scope.txtProductname;
var product_description=$scope.tarDescription;
var price=$scope.txtprice;
var unit_in_stock=$scope.txtunitinstock;
var unit_weight=$scope.txtweight;
var file = $scope.front_image;
var file2=$scope.back_image;
var file3=$scope.left_side_image;
var file4=$scope.right_side_image;
var main_image=$scope.main_image;
var large_image=$scope.large_image;
var category_id=$scope.selectedCategory.category_id;
var sub_category_id=$scope.selectedSubCategory.sub_category_id;
var sub_sub_category_id=$scope.selectedSubSubCategory.sub_sub_category_id;
var product_key=$scope.addProductOption;
var tags=$scope.txt_tags;
var aditional_information=$scope.txt_aditional_information;
var temp_color_and_size=[];
temp_color_and_size=$scope.color_and_size;
console.log(temp_color_and_size);
var uploadUrl = 'http://web.com/app/add_product';
fileUpload.uploadFileToUrl(file,file2,file3,file4,main_image,large_image, product_name,product_description,price,category_id,sub_category_id,sub_sub_category_id,unit_in_stock,unit_weight,product_key,tags,aditional_information ,temp_color_and_size, uploadUrl);
}
/* ---------------------------------------------------- Color and Sizes -------------------------------------------------- */
$scope.color_and_size=[];
$scope.Add=function(){
var c_and_s=[];
c_and_s.color_name = document.getElementById('cl1').value;
var s;
if($scope.sizes!=null)
{
for(var i=0;i<$scope.sizes.length-1;i++)
{
if($scope.sizes[i+1]>=0 && $scope.sizes[i+1]<=9)
{
}
else
{
if($scope.sizes[i+2]>=0 && $scope.sizes[i+2]<=9)
{
}
else
{
$scope.sizes = $scope.sizes.substring(0, i+1);
}
}
}
console.log($scope.sizes);
$scope.size=$scope.sizes.split(',');
c_and_s.sizes=$scope.size;
}
$scope.color_and_size.splice(0,0,c_and_s);
console.log($scope.color_and_size);
document.getElementById('cl1').value="#000000";
$scope.sizes="";
}
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file,file2,file3,file4,main_image,large_image,product_name,product_description,price,category_id,sub_category_id,sub_sub_category_id,unit_in_stock,unit_weight,product_key,tags,aditional_information,temp_color_and_size, uploadUrl){
console.log(product_name);
console.log(product_description);
console.log(price);
console.log(unit_in_stock);
console.log(unit_weight);
console.log(file);
console.log(temp_color_and_size);
console.log(product_key);
console.log(tags);
console.log(aditional_information);
var payload = new FormData();
payload.append("product_name", product_name);
payload.append('product_description', product_description);
payload.append('price', price);
payload.append('unit_in_stock', unit_in_stock);
payload.append('unit_weight', unit_weight);
payload.append('file', file);
payload.append('file2', file2);
payload.append('file3', file3);
payload.append('file4', file4);
payload.append('main_image', main_image);
payload.append('large_image', large_image);
payload.append('product_key', product_key);
payload.append('tags', tags);
payload.append('aditional_information', aditional_information);
payload.append('temp_color_and_size', temp_color_and_size);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
})
.then(function (response){
alert('Product Added Successfully');
window.location = "http://web.com/add_product"
},function (error){
});
}
}]);
Please help me to resolve this problem.
Your question is not clear to me but I think the problem is that all properties of the formData object apart from temp_color_and_size are string type and temp_color_and_size is a javascript object. This might solve your problem.
payload.append('temp_color_and_size', JSON.stringify(temp_color_and_size);
You have to deserialize JSON string on the server side.
I am fetching a list of files (which may be of any type) from mysql database and converting them to byte[] and returning all the files of a particular user as an array of files in spring boot.
Now I need to display all the files in the front end and provide an option to edit the file so that the user can remove the already existing file with the new file.
So Whenever a particular file is edited I have to upload the file from front end using angular js.
The Problem is I am getting the files as an array in response.data. I am facing a problem here like, How to edit the a particular file in that array and send the list of files to the backend to store them.I tried to traverse through array of files and store each file as a blob object, but I am not sure of what is the content type of each file as it can be any type of file(.bmp,.pdf,.docx,.tif etc).
Also I am not sure if it is the rightway to do for editing the files, because it may alter the content of the existing file or may change the type of the exixsting file.
So Please suggest me a way to get the file from the database and edit the file if necessary and then push it back to the database.
My controller and services below:-
angular.module("app").service("serviceCalls", function($q, $rootScope, $http) {
this.landOwnerEditProfile = function(email){
var differed = $q.defer();
$rootScope.config.headers.Authorization = sessionStorage.Authorization;
$http
.get($rootScope.URL + "/landownerDetails/"+email+"/", $rootScope.config,{
responseType: 'blob'
})
.then(function(response) {
console.log("coupon service success");
differed.resolve(response);
})
.catch(function(response) {
differed.reject(response);
});
return differed.promise;
};
this.updateLandOwnerProfile = function(details, email) {
var differed = $q.defer();
$rootScope.config.headers.Authorization = sessionStorage.Authorization;
var formdata = new FormData();
// console.log($("#file"));
formdata.append("email", email);
formdata.append("fname", details.user.fname);
formdata.append("lname", details.user.lname);
formdata.append("city", details.user.city);
formdata.append("phone1", details.user.phone1);
formdata.append("phone2", details.user.phone2);
formdata.append("phone3", details.user.phone3);
formdata.append("streetAddressLine1", details.user.streetAddressLine1);
formdata.append("streetAddressLine2", details.user.streetAddressLine2);
formdata.append("stripeApiKey", details.user.stripeApiKey);
formdata.append("zipcode", details.user.zipcode);
formdata.append("businessName", details.user.businessName);
formdata.append("landOwnerEditProfile", true);
// var input_files = document.getElementsByClassName("files");
// for (var i = 0; i < input_files.length; i++) {
// console.log(input_files[i].files);
// for (var file of input_files[i].files) formdata.append("file", file.name);
// }
// formdata.append("file", input_files);
// for (var key of formdata.entries()) {
// console.log(key[0] + ", " + key[1]);
// }
for (var i = 0; i < details.files.length; i++) {
formdata.append("file", details.files[i].file);
}
$http
// .post("http://localhost:8090/", formdata, {
.post($rootScope.URL + "/user/landownerDetails/editProfile/"+email+"/", formdata, $rootScope.config,{
transformRequest: angular.identity,
headers: {
"Content-Type": undefined,
// "Authorization":$rootScope.config.headers.Authorization
}
})
.then(function(response) {
// console.log(response);
if(response.data.status!=true){
throw new Error(" Details Not Updated ");
}
console.log("Details updated success");
differed.resolve(response);
})
.catch(function(response) {
console.log("rejected", response);
differed.reject(response);
});
return differed.promise;
}})
angular
.module("app")
.controller("landOwnerEditProfile", function($state, $scope, $location, serviceCalls, $filter, $stateParams,$timeout) {
$scope.files = [];
serviceCalls.landOwnerEditProfile(sessionStorage.emailId)
.then((response)=>{
console.log(response.data);
let status = response.status;
if(status===200){
let landownerDetails = response.data;
let landowner = landownerDetails.dayleasingusers;
let userdocuments = landownerDetails.userdocuments;// userdocument is an array containing the files
$scope.user = {};
$scope.property={};
$scope.user.fname = landowner.fname;
$scope.user.lname = landowner.lname;
$scope.user.streetAddressLine1 = landowner.address1;
// $scope.user.streetAddressLine2 = landowner.address2 ||'sdasd';
$scope.property.propertyType = landowner.state || 'Alabama';
$scope.user.city = landowner.city;
$scope.user.zipcode = parseInt(landowner.zipCode);
$scope.user.phone1 = !!landowner.phone?parseInt(landowner.phone.substring(0,3)):null;
$scope.user.phone2 = !!landowner.phone?parseInt(landowner.phone.substring(3,6)):null;
$scope.user.phone3 = !!landowner.phone?parseInt(landowner.phone.substring(6)):null;
$scope.user.stripeApiKey = landowner.stripeApiKey;
$scope.user.businessName = landowner.businessName;
$scope.files = [];
for(let doc of userdocuments){
let blob = new Uint8Array(doc.filedata);
$scope.files.push({file:new Blob([blob],{ type:'contentType'})}); //I am not sure of the contentType here.
// $scope.files.push({file:new Blob([doc.filedata],{ type:'multipart/form-data'},doc.filename)});
// $scope.files.push({file:new File([doc.filedata],doc.filename)});
}
}
else{
throw new Error(response.statusText);
}
})
.catch((error)=>{
console.log(error);
})
serviceCalls.updateLandOwnerProfile($scope, sessionStorage.emailId)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
})
In my angular app , I am trying to upload an excel file to web api from Angular JS but I am unable to do so .
The method in the server web api is not being hit.
The angular code looks like :
$scope.file = null;
//UPLOAD FILE CODE
var formdata;
$scope.getTheFiles = function ($files) {
console.log($files[0].type);
formdata = new FormData();
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: BasePath + 'uploadNative/UploadFiles/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
console.log(formdata);
if (formdata != null || formdata != undefined) {
$http(request)
.success(function (response) {
if (response != "Failed!") {
console.log("Succeeds");
}
else {
console.log("Failed");
}
})
.error(function () {
});
}
And the UI MVC controller which should invoke the web api controller causes exception.
public async Task<JsonResult> UploadFiles()
{
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
string url = BaseURL + "api/Upload/groupmembershipupload/";
string res = await Models.Resource.PostFileAsync(url, Token, hfc, ClientID);
var result = (new JavaScriptSerializer()).DeserializeObject(res);
return Json(result);
}
This PostFileAsync fires the exception.
using (client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
client.DefaultRequestHeaders.Add("ClientID", ClientID);
var content = new MultipartFormDataContent();
System.Web.HttpPostedFile hpf = data[0];
byte[] fileData = null;
using (var sds = new BinaryReader(hpf.InputStream))
{
fileData = sds.ReadBytes(hpf.ContentLength);
}
content.Add(new ByteArrayContent(fileData, 0, fileData.Count()));
//using (response = await client.PostAsJsonAsync(url + "?=" + DateTime.Now.Ticks, data))
using (response = await client.PostAsync(url + "?=" + DateTime.Now.Ticks, content))
{
...the response is Http Error 415 "Unsupported Media Type". It does not call the service.
Change the headers to:
headers: {
'Content-Type': 'multipart/form-data'
}
I have a POST request for a PDF document in an APIController, here's the code:
Generator pdfGenerator = new Generator();
MemoryStream ms = pdfGenerator.Generate();
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(ms)
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Tag.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
when I send my file to angular with a GET request everything works fine and I can download the pdf using:
$window.open('my_url');
A well formed 28K pdf file is created in the download folder.
But when I changed my request to a POST the file is malformed.
var pdfGetter = $resource('my_url', {}, {
sendPDFTag: { method: 'POST', url: 'my_url', responseType: 'arraybuffer' }
});
pdfGetter.sendPDFTag(info, function(data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);;
});
I tried using the FileSaver.js and I get a bad 1K pdf file in my download folder.
pdfGetter.sendPDFTag(info, function(data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'Tag.pdf');
});
What could the problem be?
Thanks
I found the solution to my problem in this question: pdf-js-render-pdf-using-an-arraybuffer-or-blob-instead-of-url
The problem was with the ng-resource that returns a promise instead of the arraybuffer, so you need to transform the data before you process the promise.
Here is the corrected code:
var pdfGetter = $resource(myUrl, {}, {
sendPDFTag: { method: 'POST', url: myUrl + "/getPdfWithPost", responseType: 'arraybuffer',
transformResponse: function(data, headersGetter) {
// Stores the ArrayBuffer object in a property called "data"
return { data : data };
}
}
});
var pdfGetter = pdfGetter.sendPDFTag(info);
pdfGetter.$promise.then(function () {
var data = pdfGetter.data;
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
});
Thank you
I want to send an avatar to my server but I have this error "You must include 'avatar' file var in your POST form data."
function getPictureSuccess(imageData) {
var image = "data:image/jpeg;base64," + imageData;
$scope.avatar = image;
}
$http({
url: api_url + 'userplus/avatar_upload/?key=' + api_key + '&cookie=' + dataCookie,
method:"POST",
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
data: {avatar: avatar}
});
Change data: {avatar: avatar} to data: {avatar: $scope.avatar}
try
imgURI = "data:image/jpeg;base64," + imageData;
var FD = new FormData();
FD.append('image', dataURItoBlob(imgURI), 'image.jpg'); // "image" This is what you get at server side so change it accord inly
FD.append("Other Param", 'other Param value ') // other parameter needed to post
$http.post('Your Url', DataObj, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
}).then(function(responce) {
responce.data;
})
// And here is your helper function
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], {
"type": mimeString
});
return bb;
}