How to send image to server on AngularJS? - javascript

I am trying to send image to server with some additional data. My issue is that the image is not getting saved on server where other recordings are.
below is my .html code :
<div class="widget uib_w_4 d-margins" data-uib="media/file_input" data-ver="0">
<input type="file" name="image" id="image"
accept="image/jpeg, image/png, image/gif"
ng-model="image" class="ng-pristine ng-untouched ng-valid">
</div>
<div class="widget uib_w_5 d-margins" data-uib="media/text" data-ver="0">
<div class="widget-container left-receptacle"></div>
<div class="widget-container right-receptacle"></div>
<div>
<p>Username:</p>
</div>
</div>
JS code
< script >
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.SendData = function()
var data = $.param({
image: $scope.image,
username: $scope.username,
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;
charset = utf - 8;
'
}
}
var param = getParameterByName('id');
$http.post('myrurl.php', data, config)
.success(function(data, status, headers, config) {
window.location.href = 'view.html';
})
.error(function(data, status, header, config) {
alert('Please retry');
});
};
});
< /script>
I tried to to print the value in PHP using print_r($_REQUEST);
The value of image is null.
How can I send my image to the server?

Pretty easy. A good approach can be to Base64 encode the image, then send that Base64 to the server; the best part is that PHP natively supports decoding Base64.
You can do something like:
<!-- In your HTML file -->
<input type="file" id="file" />
<input type="submit" ng-click"uploadFile" value="Upload File"/>
Then, in your JavaScript:
$("#file").on('change', function(event) {
var reader = new FileReader();
reader.onload = function( loadEvent ) {
$scope.fileData = loadEvent.target.result;
$scope.$apply();
};
reader.readAsDataURL( event.target.files[0] );
});
$scope.uploadFile = function() {
if ( $scope.fileData === null || $scope.fileData === "" || !($scope.fileData) ) {
alert("No file has been uploaded");
return;
}
var dtx = eval("(" + atob($scope.fileData.substring("data:application/json;base64,".length)) + ")");
$http.get( 'yourScript.php?data=' + encodeURIComponent( JSON.stringify(dtx) ) ).then( function(response) {
if( response.data.status_code == 200 ) {
// Done!
} else { ERROR }
});
};
Lastly, in your PHP file you can:
$imageData = base64_decode( $_GET[ 'data' ] ); // Now you have a binary image file. Do whatever you want!

Related

unable to upload multiple files in Angularjs

Hi I am trying to upload multiple files in angularjs. I am not able to upload multiple files as it is giving me error eferenceError: $upload is not defined
This is my html code.
<div class="upload-button" ng-repeat="file in files">
<div class="upload-button-icon">
<img src="images/folder-small.png">
<div class="upload-text">{{file}}</div>
<input type="file" id="file1" name="file1" />
</div>
</div>
<input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">
Below is my angularjs code to upload file.
$scope.upload = function () {
debugger;
var fileuploadurl = baseurl + 'api/Customer/UploadLeaseFiles/' + LoginID + '/' + "GOSI";
for (var i = 0; i < $scope.files.length; i++) {
var $file = $scope.files[i];
$upload.upload({
url: fileuploadurl,
file: $file,
progress: function (e) {
// wait...
}
})
.then(function (data, status, headers, config) {
alert('file is uploaded successfully');
});
}
alert('file is uploaded successfully');
};
Above code gives me error $upload is not defined. May i know where i am doing wrong in the above code? Any help would be appreciated. Thank you.

why does my postback in Chrome not refresh my page

I have a postback that should refresh my page and reload page. When the page reloads it should display an image or an uploaded link or an uploaded document link or something. This works great when I run locally, but when I have deployed the same code to my host server, the page reloads with blanks, and the user must hit refresh to see the results. the following code snippet asks the user to upload an image, and then performs an update:
markup:
<form id="updateLogo" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-12">
<h5 class="red"><b>(Image sizes are limited to 1 Megabyte)</b></h5>
Select File:
<input class="form-control" type="file" name="file" id="file" required="required" />
<input class="form-control" type="hidden" name="communityId" id="communityId" value="#ViewBag.CommunityId" />
</div>
<div class="col-lg-6 col-md-12">
Current Profile Image:
<img src="#ViewBag.LogoImage" class="img-responsive img-circle" style="width:150px; height:150px" />
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-12">
<input type="submit" value="Upload Image" class="btn btn-habitat" id="updtLogo">
</div>
</div>
</div>
</form>
javascript with ajax :
$("#updtLogo").click(function () {
// Host
var hostname = location.hostname;
var host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
// New Form data including the newly uploaded file
var formSerialized = $("#updateLogo").serializeArray();
var formdata = new FormData();
var logofile = $("#file")[0].files[0];
// Supporting Assets (i.e. uploaded files go here)
for (i = 0; i < $("#file")[0].files.length; i++) {
formdata.append("File", $("#file")[0].files[i]);
}
$.each(formSerialized, function (i, field) {
formdata.append(field.name, field.value);
});
var communityId = $("#communityId").val();
var fileLogo = $("#file").val();
// Only allow if file size is less than 1MB
if (logofile.size < (1024 * 1024)) {
$.ajax({
type: "POST",
url: host + "/Communities/UploadLogo/" + communityId + "?logo=" + fileLogo,
contentType: false,
processData: false,
data: formdata,
success: function () {
console.log('success!!');
}
});
window.location.reload();
} else {
var errorMsg = 3;
$(".modal-dialog").css({
"left": 0,
"top": 200,
});
$(".modal-body").css({
"background-color": "green"
})
$(".modal-title").text("Error Uploading Logo Image");
var url = host + "/Communities/ErrorMessageDialog/" + communityId + "?errorMsg=" + errorMsg;
$("#inviteDialog").load(url, function () {
$("#inviteModal").modal("show");
})
}
return false;
});
MVC ActionResult
[HttpPost]
[Authorize]
public ActionResult UploadLogo(int id, string logo)
{
// Uploaded data files go here
HttpPostedFileBase file = Request.Files[0];
var logoFile = file.FileName != null ? file.FileName : logo;
if (logoFile != null || logoFile != "")
{
var fileName = Path.GetFileName(logoFile);
var host = ConfigurationManager.AppSettings["hostroot"];
if (System.Web.HttpContext.Current.Request.IsLocal)
host = "";
var communityId = id;
// var fileName = file.FileName;
var directory = Server.MapPath("~/CommunityStorage/" + communityId + "/Logo/");
var virtualPath = host + "/CommunityStorage/" + communityId + "/Logo/";
// Create a new directory for the community if it does not exist based on their community id
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var path = Path.Combine(directory, fileName);
file.SaveAs(path);
// Save file path to the Communities Table
var community = db.Communities.Where(x => x.CommunityId == communityId).SingleOrDefault();
if (community == null)
return RedirectToAction("Index", "login");
// Update the Logo in the communities table
community.LogoPath = virtualPath + fileName;
db.SaveChanges();
}
return View();
}
From the comments:
the typical pattern for ajax follows as:
$.ajax({ ... success: function(data) { /* Do stuff here */ } });
If you are looking to reload the page after you receive your data do so in the callback like so:
$.ajax({
...
success: function(data) {
window.location.reload();
}
});
Be careful when reloading the page: JavaScript data doesn't persist after page reload unless you're using cookies / caching.

angular ng-file-upload on PUT reader.result is undefined

I'm trying to update a module without uploading a new image. The problem is that if I do not upload a new image and instead try and use the image that i read back from the api then it says read.result is undefined when debugging. I think the reader is expecting an image stream and i'm giving it a url. Not sure how to fix this.
The API takes a DataURL which is the image, then stores it and puts image path/url in ImageURLPATH.
Code:
angular.module('Services.modulesPUT', [])
.service('modulesPUTSrvc', function (baseSrvc, $http,modulesGETSrvc,$rootScope,$state, myConfig) {
var fObject = {};
fObject.myForm = {};
fObject.details = {};
fObject.imgObject = {};
fObject.put = function ()
{
var imageData;
if (fObject.myForm.$valid)
{
var reader = new window.FileReader();
reader.readAsDataURL(fObject.details.ImageURLPath);
reader.onloadend = function () {
$rootScope.loading = true;
var result = $http({
method: "PUT",
dataType: 'json',
data: {
"DataURI": reader.result
},
url: myConfig.baseURL + 'odata/Modules(' + fObject.details.ModuleId + ')'
});
result.success(function (data) {
$rootScope.loading = false;
baseSrvc.toastMessage('Module has successfully been updated.');
$state.go('base.modules.get');
});
result.error(function (data) {
$rootScope.loading = false;
baseSrvc.returnError(data);
});
};
}
else
{
baseSrvc.toastMessage('Please input all required fields.');
};
};
return fObject;
});
<div class="md-block" flex-gt-sm>
<div class="imageUpload">
<md-tooltip md-direction="left">
Click here to select your image
</md-tooltip>
<div class="button"
required
ngf-select
ng-model="srvcObject.details.DataURI"
name="file"
ngf-pattern="'image/*'"
ngf-accept="'image/*'"
ngf-max-size="20MB"
><span ng-show="!srvcObject.details.DataURI">Select <br/> Course Image</span></div>
<div class="preview"
ngf-src="srvcObject.details.ImageURLPath"
ngf-background="srvcObject.details.ImageURLPath"></div>
</div>
</div>

How to get response using Kendo file upload async method?

I am using kendo to upload files from the client everything is working as expected while loading , But here i have question related to url when we upload files i am using url in the config when file loads succesfully i have response from the server.
How can i extract data from response using kendo async saveUrl method ?
main.html
<div class="form-group col-md-6">
<div class="col-md-6">
<label for="prcFileUploadField">File:</label>
</div>
<div class="col-md-6">
<input name="file" type="file" kendo-upload="fileAttachment" k-upload="addMorePostParameters" k-success="onSuccess" k-error="onError" k-options="fileAttachmentOptions" k-select="onSelect" k-remove="onUploadRemove" />
</div>
</div>
ctrl.js
angular.module('App').controller('PrcUploadCtrl',function($scope,$timeout,$rootScope,prcUploadConfig){
'use strict';
var fileData = [];
$scope.fileAttachmentOptions = prcUploadConfig.fileAttachmentConfig;
$scope.prcUploadGridOptions = prcUploadConfig.getPrcUploadDataGrid;
prcUploadConfig.getPrcUploadDataGrid.dataSource='';
$scope.onSelect = function (e) {
fileData = e.files;
var message = $.map(e.files, function(file) { return file.name; }).join(", ");
console.log(message);
console.log(JSON.stringify(fileData));
};
//if error
$scope.onError = function() {
console.log("loggin error");
$timeout(function () {
var filesToBeRemoved = $scope.fileAttachment.wrapper.find('.k-file');
$scope.fileAttachment._removeFileEntry(filesToBeRemoved);
},5000);
}
});
config.js
fileAttachmentConfig: {
async: {
saveUrl: 'app/upload/uploadAttch',
removeUrl: 'remove',
removeVerb: 'DELETE',
autoUpload: false
},
template: '<span class=\'file-name-heading\'>Name:</span> <span>#=name#</span><button type=\'button\' class=\'k-upload-action\'></button>'
}
You can always get a response body from successful requests like this:
$scope.onSuccess = function(e) {
var response = e.response;
//...
}

AJAX Show Image after Upload

i working on uploading files using ajax for almost 3 hours and successfully managed to make it work, please check the code:
View
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Image(s)", new { #class = "control-label col-sm-3" })
<div class="col-sm-5">
<input type="file" name="UploadFile" id="UploadFile" accept=".png, .jpg, .gif" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<input type="button" value="Save" id="save" class="add btn btn-primary" />
<div style="color:red">
#ViewBag.error
</div>
</div>
</div>
</div>
<div style="margin-top: 17px;">
#foreach (var item in Model.Content)
{
<div class="gallery">
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete btn btn-danger" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
Controller
[HttpPost]
public ActionResult Create(Photo photo)
{
var model = new Photo();
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
model.Description = photo.Description;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
model.ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
// Save thumbnail size image, 100 x 100
SaveToFolder(img, fileName, extension, new Size(200, 200), model.ThumbPath);
// Save large size image, 800 x 800
SaveToFolder(img, fileName, extension, new Size(600, 600), model.ImagePath);
}
// Save record to database
model.CreatedOn = DateTime.Now;
db.Photos.Add(model);
db.SaveChanges();
}
return Json("File Uploaded Successfully");
}
JQuery/AJAX
<script type="text/javascript">
$('#UploadFile').on('change', function (e) {
var $this = $(this);
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '/Home/Create',
contentType: false,
processData: false,
data: data,
success: function (result) {
console.log(result);
//add code to refresh the gallery with the new uploaded image
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("Error! This browser does not support file upload, please change your browser");
}
}
});
</script>
SavetoFolder
private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
{
// Get new image resolution
Size imgSize = NewImageSize(img.Size, newSize);
using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
{
newImg.Save(Server.MapPath(pathToSave), img.RawFormat);
}
}
NewImageSize
public Size NewImageSize(Size imageSize, Size newSize)
{
Size finalSize;
double tempval;
if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
{
if (imageSize.Height > imageSize.Width)
tempval = newSize.Height / (imageSize.Height * 1.0);
else
tempval = newSize.Width / (imageSize.Width * 1.0);
finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
}
else
finalSize = imageSize; // image is already small size
return finalSize;
}
but the problem is i have to refresh the browser to see the added image, what should i put in ajax on sucess upload to add the image dynamically without refreshing browser?
Since you are having option to upload multiple images I would suggest to go with below approach:
your controller now would look like:
[HttpPost]
public ActionResult Create(Photo photo)
{
List<Photo> model = new List<Photo>();
//create list of photo model
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
string thumpath,imagepath = "";
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.Add(new Photo(){
Description=photo.Description,
ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension),
ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension),
CreatedOn=DateTime.Now
});
//fill each detail of model here
thumpath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
//separate variables to send it to SaveToFolder Method
imagepath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
SaveToFolder(img, fileName, extension, new Size(200, 200), thumpath);
SaveToFolder(img, fileName, extension, new Size(600, 600), imagepath);
}
}
foreach(var md in model)
{
//loop again for each content in model
db.Photos.Add(md);
db.SaveChanges();
}
return Json(new {model=model },JsonRequestBehavior.AllowGet);
//return the model here
}
in ajax success you can create the image with the model returned values as below:
success: function (result) {
var model = result.model;
$(model).each(function (key,value) {
$('<img />').attr({
src: value.ThumbPath
}).appendTo("body");
//note you can append it to anywhere, like inside container or something
})
}
I would set the src attribute of the img tag usign jQuery in your success function:
success: function (result) {
$("img").attr('src' , '/path/to/your/img');
},
If you don't know the public path to your image on client side you can use the response object:
return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}");
There is a few possibilities, which to use depends on pictures size etc.
Personaly I (if images are not too big) would on server side convert image ot base64 and return it with ajax and display the data returned from server, of course it would need conversion as well.
Check out this article, i think i'll help you :)
Base64 encoded image

Categories