Pass a picture from Angualrjs front-end to Laravel back-end - angularjs

I'm building an app in which I need to upload an image with angularjs, pass it with other data to a save() method written in laravel, what is the simplest way to do it?
in my html I have a title field and an image uploader:
<form>
<input type="text" required ng-model="selectedAD.title">
<input type="file" name="file" ngf-max-size="2MB" required ng-model="selectedAD.image"/>
<a class="btn-portal" type="submit" ng-click="saveAD()">
</form>
and inside my js file, I pass these data into the save route which goes to the store() function in laravel and moves the image into a folder, like this:
$scope.selectedAD = ad;
$scope.saveAD = function(){
$scope.managementErrors = [];
adsResource.save($scope.selectedAD,function(success){
$('#ads-modal').modal('hide');
showSuccessAlert($scope,$timeout, getSuccessMessages(success),$('#successMessages'));
$scope.getAdsTimeout();
},function(error){
$scope.managementErrors = getErrorMessagesUpdate(error);
});
this way the image is not passed to laravel processing code, it instead passes null to the store function, any helpful guides ?

Related

How to insert data into mysql sent by react app using sails js

I have a react form like this:
return (
<form action="" method="post">
<input type="text" name="aaa" />
<input type="submit" />
</form>
);
I have started sails js using sails lift --port=4010
But now, I have no idea, how to send the data to sails? What should be the URL in action?
When I open localhost:4010 it says Not Found
Firstly you need to generate model in Sails.js and after define attributes there.
If you bluprints is true on your config then posting your values to the "localhost:4010/{{modelName}}" must work automatically. But if you want to change the route you can override it in config/routes.js

Upload files with Angular with a post containing other form data

I have followed countless examples (from here and other sites) that explain how you upload files from Angular to a web server. I am happy with the solution of using angular-file-upload and processing the data on the server (Node) with Multer.
What I haven't been able to find is a way to upload files from the form with a post that contains all the other controller data.
controller:
$scope.files = [];
$scope.name = "";
$scope.post = //$http post to server from service
view:
<input type="text" ng-model="name">
<input type="file">
<button ng-click="post()">Send post without page refresh</button>
Is there a way I can send the [name] and the [files] in the same post? If I send with multi part data will that be ok for [name] and [files]? Do I need to send two separate posts?
At the moment, my working example submits with a form action of 'post' and an enctype of "multipart/form-data". But I don't want the page to refresh and I want to send [name] and [files] from the scope... do I need to attach the files from the form to the scope or get the scope to pull the files from the DOM?
You can push formData to file before upload.
$scope.uploader.onBeforeUploadItem = function(fileItem) {
fileItem.formData.push({name: $scope.name});
};
Please look through the demo for complete solution :)
Plunkr
<form>
<input type="text" placeholder="Enter Name here" ng-model="newCountry.Name" />
<label>Choose 1 or more files:</label>
<input type="file" ng-files="AddnewCountryFlag($files)" multiple />
<h3>Try Uploading Image file. It will preview your image.</h3>
<div ng-repeat="item in imagesrc">
<img src="{{item.Src}}" />
<label>{{item.Size}}kB</label>
</div>
<input type="submit" value="Send Data" ng-click="AddCountry()" />

Uploading multiple files with angular-file-upload

I'm using angular-file-upload to upload images along with form data to my server. I've been able to do that successfully one image at a time.
My problem is that in my form I need to upload two images, using separate inputs (as well as send along other form data). My reasoning for using separate inputs is that one of my images is a thumbnail image and the other is a hero image. I need the ability to distinguish between them and insert the file paths for each into their respective columns in my database.
I read through this github issue that went through how to upload multiple files using the same input, but I wasn't able to find anything about uploading multiple files using different inputs. Maybe I'm misunderstanding them though.
Right now, if I try to select a header image, it only changes the value of the thumbnail image.
Here is my form:
<form>
...(other text form inputs above)...
<div class="form-group">
<label class="col-sm-2 control-label"> Teaser</label>
<div class="col-sm-8>
<input class="form-control" filestyle="" accept=".png,.gif,.jpg,.jpeg" data-button-text="Choose image" type='file' data-classbutton='btn btn-default' data-classinput="form-control inline" nv-file-select='' uploader='uploader' options="{'field': 'thumbnail_url'}"
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Header Image</label>
<div class="col-sm-8>
<input class="form-control" filestyle="" accept=".png,.gif,.jpg,.jpeg" data-button-text="Choose image" type='file' data-classbutton='btn btn-default' data-classinput="form-control inline" nv-file-select='' uploader='uploader' options="{'field': 'header_url'}"
</div>
</div>
</form>
And here is how I am sending the file to my server (on the onCompleteAll callback I am sending my form data to the server):
$scope.uploader = new FileUploader({
url: '/laravel/public/admin/events/thumbnail_url/file_upload',
alias: 'files',
headers: {
// 'X-CSRF-Token': n/a
},
onBeforeUploadItem: function(item) {
/* Laravel file name alias */
item.alias = 'file';
},
onSuccessItem: function(fileItem, response, status, headers) {
$scope.newEventForm[fileItem.field] = '/laravel/public/uploads/events/' + response.filename;
},
onCompleteAll: function() {
/* Now ready to save form data */
AdminEvent.save($scope.newEventForm).$promise.then(function(response) {
$scope.events.push(response.data);
toaster.pop('success', 'Added', 'Event added successfully.');
});
}
});
I faced the same issue with ng-file-upload but I did not used angular-file-upload.
So may be this solution helpful for you.
In my app I have user profile image and background image.
where profile image input value I send with file option of ng-file-upload but it did not provide other option to send second file input value.
TO resolve that What I did
Created second file input and used that input model same as my table attribute like ng-model="user.bg_avatar" where bg_avatar is my background image attribute in rails.
Now You can get second file input value with user object(user.bg_avatar) in angular controller which we will send to rails and when rails get it save that with other user attribute.
But don,t forgot to permit this attribute.

Have AngularJS perform logic on form inputs when form submits

I currently have a form like the following:
<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" action="{{trustSrc(SUBMIT_URL)}}">
<input type="text" name="firstinput" ng-model="first"/>
<input type="text" name="secondinput" ng-model="second"/>
<input type='submit'/>
</form>
And a controller like so:
$scope.first = "first";
$scope.second = "second";
$scope.SUBMIT_URL = DATABASE_URL + "forms/submit/";
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
};
And when I submit this form as is, it works just fine with the backend. However I now need to use ng-submit in place of the standard HTML form submit because I need to run a find and replace in $scope.first. The backend expects the data to be posted exactly in the way the original HTML form does. How do I use $http or $resource to post in the exact same format as the HTML form?
It is not very clear what you are trying to accomplish. But, you should tidy up your code a bit, to make the implementation easier:
Don't use different variables for each input's field. Instead, use an object with different keys.
Use ng-click (or ng-submit) for your submission. Action will go inside your JS logic.
Use the novalidate attribute so that Angular can properly format, and validate your form on its own (and you don't get confusing cross-browser effects).
With those in mind, your new markup would be:
<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" novalidate>
<input type="text" name="first" ng-model="form.first" />
<input type="text" name="second" ng-model="form.second" />
<button ng-click="submit">Submit</button>
</form>
Your JS directive is then:
app.directive('form', function($http)
{
return function(scope, element, attrs)
{
// Leave this empty if you don't have an initial data set
scope.form = {
first : 'First Thing To Write',
second : 'Second item'
}
// Now submission is called
scope.submit = function()
{
// You have access to the variable scope.form
// This contains ALL of your form and is in the right format
// to be sent to an backend API call; it will be a JSON format
// Use $http or $resource to make your request now:
$http.post('/api/call', scope.form)
.success(function(response)
{
// Submission successful. Post-process the response
})
}
}
});

How do you define POST parameters using inputs in the request body?

I am making a POST request to a RESTFUL api and the only way I can pass the parameters is if I add them into the URL used in the forms 'action' parameter. As soon as I take those parameters and put them down into the form's body component the request no longer works. My question is how do I use the inputs within the form to define the request parameters instead of the embedding the parameters into the action URL?
I do notice that when I submit the request the request body parameters show up, but the actual request fails saying that the parameters are not there.
Here is the HTML:
<form target="hiddenIframe" method="POST" action="/rest/bpm/wle/v1/process/5853?action=addDocument&name=test123&docType=file&parts=none&accept=application/json&override-content-type=text/plain" enctype="multipart/form-data">
<input type="text" name="instanceId" value="5823" />
<input type="text" name="name" value="myTestQ1" />
<input type="text" name="docType" value="file" />
<input id="myFileName" type="file" name="data" />
<input type="submit"/>
</form>
<iframe name="hiddenIframe" id="hiddenIframe" style="display: none;" />
As you can see the action in the form tag is very long and is not dynamic... I would like to only have "/rest/bpm/wle/v1/process/" there, but when I do the upload fails.
I'd use some Javascript. Add an onchange to all the mandatory input fields. And the change method you'll be calling can update your action url with the new data from the form field.
Something like:
<input type="text" name="instanceId" value="5823" onchange="updateInstanceID()" id="instanceid" />
action="/rest/bpm/wle/v1/process/5853?action=addDocument&name=test123&docType=file&parts=none&accept=application/json&override-content-type=text/plain"
Now, your Javascript should have that method.
function updateInstanceID() {
var val = document.getElementById("instanceid").value;
var form = document.forms[0]; // assuming only one form on the page.
....
}
Now you can access your form.action field and update it accordingly.

Resources