Upload files with Angular with a post containing other form data - angularjs

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()" />

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 a picture to database with laravel

i ve created a database in localhost and table in it called gallery. I want to upload and store pictures there but i m stuck.. Can you please give me any guides or tutorial how to do it? Thanks.
upload file just refer to laravel document
for example photo is the name fo file in form
<form action="xxx" method="post" enctype="multipart/form-data">
<input type="file" name="photo" />
<input type="submit" value="update" />
</form>
store the file then return file's path in filesystem
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
then store the $path to your database
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and
move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}

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

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 ?

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.

Accessing Restangularized Data

I am using Restangular in my Angular app. I can successfully pull data from by backend. However, I am having difficulty getting it to update the data after submitting a form. The PUT method will work and will send the request to the API but the payload isn't correct. It is sending the original data. I can't seem to get the restangularized data to show up on my page.
I can make the response for my data available in the views by doing:
$scope.user = Restangular.one('user', 1234).get().$object;
The user information does not show up unless I put in $object.
If I just use:
$scope.user = Restangular.one('user', 1234).get();
My views don't display the user information, putting {{user}} will be {"restangularCollection":false,"reqParams":null,"parentResource":null}.
As I understand it, Restangular appends the different functions in order to enable the restful actions which is why Restangular.one('user', 1234).get().$object wouldn't be preferable.
I tried putting in setResponseExtractor() into my config per the documentation (https://github.com/mgonto/restangular#how-can-i-access-the-unrestangularized-element-as-well-as-the-restangularized-one) but it is overwritten by setResponseInterceptor() which I need to transform the response from getList() into an array.
Here is my controller:
props.controller('UserEditController', function($scope, $routeParams, $location, Restangular) {
var UserEdit = Restangular.one('users', $routeParams.userId).get();
$scope.user_edit = Restangular.copy(UserEdit);
console.log($scope.user_edit);
$scope.save = function() {
$scope.project.put().then(function() {
$location.path('/');
});
});
My form:
<h1>Edit Profile</h1>
<form ng-submit="save_user()">
<label for="first_name">First Name:
<input type="text" name="first_name" ng-model="user_edit.first_name" ng-value="user_edit.first_name" /><br />
<label for="last_name">Last Name:
<input type="text" name="last_name" ng-model="user_edit.last_name" ng-value="user_edit.last_name"/><br />
<label for="email">Email:
<input type="text" name="email" ng-model="user_edit.email" ng-value="user_edit.email"/><br />
<label for="position">Position:
<input type="text" name="position" ng-model="user_edit.position" ng-value="user_edit.position"/><br />
<button type="submit">Save</button>
Cancel
</form>
I've looked over the Restangular example on Plunker (http://plnkr.co/edit/d6yDka) and it got me aways but I can't seem to figure this out. It is driving me crazy. Can someone help?
This only addresses the .$object portion of the question.
Restangular does everything with promises. Before the response data can be accessed, the promise has to be fulfilled/resolved.
// Assign data to $scope once response is returned.
Restangular.one('users', $routeParams.userId).get().then(function(user){
$scope.user_edit = user;
});
Then putting {{user_edit}} in your view should display the user data.

Resources