How to send file to Sails from AngularJS without using custom directives? - angularjs

So I need to upload an image to the server. Right now it works only with a POST request made via HTML. But I need to send other data and do other stuff before uploading it, so I'd like to send the request inside an Angular controller, using $http.post(...). I've seen some really complex solutions using custom directives, but I'd like to know if there's anyway to do something straight forward like:
$scope.uploadPhoto = function(){
var fd = new FormData();
fd.append("uploadFile", $scope.file);
$http.post('file/upload', fd);
}
Working code:
HTML:
<form id="uploadForm"
enctype="multipart/form-data"
action="/file/upload"
method="post">
<input type="file" name="uploadFile" />
<input type="submit" value="submit"/>
</form>
Sails Controller:
upload: function (req, res) {
var uploadFile = req.file('uploadFile');
uploadFile.upload(
{ dirname: '../../assets/images',
saveAs: function(file, cb) {
cb(null, file.filename);
}
}, function onUploadComplete (err, files) {
if (err) return res.serverError(err);
res.json({status:200,file:files});
});
}

Related

AngularJS $http PUT request

I am buiding a CRUD apps with AngularJS and Django REST API.
I have created get and post method successfully but not getting how to put request. i tried stackoverflow lots of problem and youtube but i couldnt sort it out.
my current controller is:
app.controller('crudCtrl', function($scope, $http) {
$http.get("http://127.0.0.1:8000/api/v1/contact/?format=json")
.then(function(response) {
$scope.contacts = response.data; //this is get method that displayed all the list of contact
});
$scope.formModel = {}; // this is same input.js, it is POST method to to send data to database
$scope.onSubmit = function () {
console.log("hey, i am submitting");
console.log($scope.formModel);
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel).
success(function (data) {
console.log(":)");
}).error(function (data) {
console.log(":(");
});
};
$scope.selectUser = function (contact) {
console.log(contact); // it will select the data exactly where you click
$scope.clickedUser = contact;
};
$scope.updateUser = function (argument) { // it will get the form editable exactly which contact you clicked
};
});
and my edit view is, when i click on edit buttion, the form will be appear:
<form>
<input type="text" ng-model="clickedUser.userid">
<input type="text" ng-model="clickedUser.name">
<input type="text" ng-model="clickedUser.email">
<input type="text" ng-model="clickedUser.phone">
<button type="submit" ng-click="updateUser()" data-dismiss="modal">Submit</button>
</form>
Point to be noted, the edit form working nice on client side but it doesnt send the data to backend/API/Database.
can anyone tell me how can i do $http.put request? i tried w3school, youtube, and stackoverflow problem.
i got huge solution but i couldnt solve it.
this is my api endpoint for anything: http://127.0.0.1:8000/api/v1/contact/ so if i want to update particular field, i have to go through this url: http://127.0.0.1:8000/api/v1/contact/1 in the end of the url is id
I hope it is clear to you
You can try this as well
$http({method: "PUT", url: URL}).
then(
function(response) {
}, function(response) {
});
Can you just use angular put?
See: https://docs.angularjs.org/api/ng/service/$http#put
var clientData = {
text: "Put this somewhere"
};
$http.put( url, clientData ).then( function( serverResponse ) {
console.log(serverResponse);
},( error )=>{
console.log(serverError);
});

Upload file from AngularJS controller to Spring writtin in Kotlin

There are a few similar questions already on StackOverflow. I have gone through some of them, but they did not work for me. So please do not mark this question as duplicate.
I want to upload a file using AngularJS to Spring Controller written in Kotlin. I have written the code below in order to do so, but it does not work. I get a 404 bad request response with a message that Required request part 'file' is not present
Input
<form class="col-xs-12 col-sm-4 form-inline " ng-submit="$ctrl.saveFiles()">
<div class="form-group">
<label for="file-upload" class="custom-file-upload">
Choose File
</label>
<input id="file-upload" type="file" file-model="$ctrl.file" name="file"/>
</div>
<div class="form-group">
<button class="btn btn-primary pull-right" type="submit">Submit</button>
</div>
</form>
file-model directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
I have copied this directive from this question
$ctrl.saveFiles() function
$ctrl.saveFiles = function () {
// var file = document.getElementById("file-upload").files[0]
var formData = new FormData();
formData.append("file", $ctrl.file);
console.log(formData.has("file")); // true
var url = '/upload',
config = {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
};
return $http.post(url, formData, config)
};
Spring #bean
#Bean
open fun multipartResolver(): MultipartResolver {
val multipartResolver = CommonsMultipartResolver()
multipartResolver.setMaxUploadSize(500000000)
return multipartResolver
}
Spring #PostMapping method
#PostMapping(value = "/upload")
#Throws(Exception::class)
fun uploadFile(#RequestParam("file") file: MultipartFile): String {
return "Upload file"
}
Request header
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4829202
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJ8BRhjvMRLt9UdRS
As you see though I use Kotlin, It is totally fine to answer in Java.
This was my first time uploading a file using AngularJS and Spring. There are some who uses CommonsMultipartResolver. I had done so. However, I did not need to use it.
It was due to using CommonsMultipartResolver that I could not upload file. I removed the code below and it works as expected. However, for some reason, I can not upload as large files as an unsplash photo
#Bean
open fun multipartResolver(): MultipartResolver {
val multipartResolver = CommonsMultipartResolver()
multipartResolver.setMaxUploadSize(500000000)
return multipartResolver
}

Back& File Upload Support - JSON

I'm currently trying to get the file upload working but hitting a problem in that the form is uploading the payload with multipart form data instead of a JSON object.
Back& will only accept a JSON object with filename and filedata inside, but I can't figure out how to accomplish this with ng-admin.
My code currently looks like this:
.uploadInformation( { 'url': BackandProvider.getApiUrl()+'/1/objects/action/games', 'params': {'name':'files'}, 'headers': { 'Content-Type': false }, 'data': data })
I see you are using BackandProvider so to bypass this you can implement the upload yourself.
From Backand docs
<body class="container" ng-app="app" ng-controller="DemoCtrl" ng-init="initCtrl()">
<h2>Backand Simple Upload File</h2>
<br/>
<form role="form" name="uploadForm">
<div class="row">
<img ng-src="" ng-show="imageUrl" />
<input id="fileInput" type="file" accept="*/*" ng-model="filename" />
<input type="button" value="x" class="delete-file" title="Delete file" ng-disabled="!imageUrl" ng-click="deleteFile()" />
</div>
</form>
</body>
// input file onchange callback
function imageChanged(fileInput) {
//read file content
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
upload(file.name, e.currentTarget.result).then(function(res) {
$scope.imageUrl = res.data.url;
$scope.filename = file.name;
}, function(err){
alert(err.data);
});
};
reader.readAsDataURL(file);
};
// register to change event on input file
function initUpload() {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
imageChanged(fileInput);
});
}
// call to Backand action with the file name and file data
function upload(filename, filedata) {
// By calling the files action with POST method in will perform
// an upload of the file into Backand Storage
return $http({
method: 'POST',
url : Backand.getApiUrl() + baseActionUrl + objectName,
params:{
"name": filesActionName
},
headers: {
'Content-Type': 'application/json'
},
// you need to provide the file name and the file data
data: {
"filename": filename,
"filedata": filedata.substr(filedata.indexOf(',') + 1, filedata.length) //need to remove the file prefix type
}
});
};

Store File Locally via Mongoose Crate with MEAN app

I'm having a bit of trouble setting up Mongoose Crate with my REST API using the MEAN stack. I'm pretty new to the whole thing so take it easy on me. I want to be able to upload a file to a local directory and then display that image within the controller. My route is setup as follows:
router.post('/posts', auth, function(req, res, next) {
var post = new Post(req.body);
post.author = req.payload.username;
// Mongoose Crate attach method
post.attach('image', req.files.image, function(err, post) {
if(err){ return next(err); }
post.save(function(err, post) {
if(err){ return next(err); }
res.json(post);
});
});
});
This is my Post model:
var mongoose = require('mongoose');
var crate = require('mongoose-crate');
var LocalFS = require('mongoose-crate-localfs');
var PostSchema = new mongoose.Schema({
title: String,
author: String
});
PostSchema.plugin(crate, {
storage: new LocalFS({
directory: './public/uploads'
}),
fields: {
image: {}
}
});
mongoose.model('Post', PostSchema);
And my controller:
app.controller('FeedCtrl', [
'$scope',
'posts',
function($scope, posts) {
$scope.posts = posts.posts;
$scope.addPost = function() {
posts.create({
title: $scope.title,
author: $scope.author,
image: $scope.image
});
$scope.title = '';
}
}
]);
And on the front end:
<form ng-submit="addPost()" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="image" id="image">
</div>
<div class="message">
<input type="text" placeholder="Title" ng-model="title">
</div>
<button type="submit"></button>
</form>
<div>
<h3>{{post.title}}</h3>
<img src="{{post.image}}"/>
<span>posted by <a>{{post.author}}</a></span>
</div>
I read that by using Express you can get an uploaded file by just the input name and using req.files but I can’t seem to get that too work within the scope. If I’m reading that Mongoose Crate plugin correctly, it should save it to a directory of your choice (using the mongoose-crate-localfs plugin), by adding it to the “Post” model, and send back an array of the file meta data. I'm not able to retrieve any data after the post.
I feel like that scene in Seinfeld when they’re trying to write the script: https://www.youtube.com/watch?v=q9eDwHznMas. “Now we need something here…”. I just don’t know what it is. If someone can please take a look and please get me out of this funk that would be amazing. Thank you so much!
Express does not come with a multipart parser out of the box, req.files will be undefined if you are not using a multipart parsing middleware. A good multipart middleware to check out is multer, very easy to use. Also if you are planning making this an XHR request you will need to use the FormData api, and explicitly tell angular not to process the data. Im sure there are many good third party solutions but here is an article worth reading.

AngularJS: how to implement a simple file upload with multipart form?

I want to do a simple multipart form post from AngularJS to a node.js server,
the form should contain a JSON object in one part and an image in the other part,
(I'm currently posting only the JSON object with $resource)
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
all the examples I can find are for wraping jQuery plugins for drag & drop. I want a simple upload of one file.
I'm new to AngularJS and don't feel comfortable at all with writing my own directives.
A real working solution with no other dependencies than angularjs (tested with v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You can use the simple/lightweight ng-file-upload directive.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function($files) {
Upload.upload({
url: 'my/upload/url',
file: $files,
}).progress(function(e) {
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}];
It is more efficient to send a file directly.
The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$scope.upload = function(url, file) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
return $http.post(url, file, config);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.
To send multiple files, see Doing Multiple $http.post Requests Directly from a FileList
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:
Working Demo of "select-ng-files" Directive that Works with ng-model1
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>
$http.post with content type multipart/form-data
If one must send multipart/form-data:
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="fdata.UserName">
<input type="text" ng-model="fdata.FirstName">
<input type="file" select-ng-files ng-model="filesArray" multiple>
<button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
var fd = new FormData();
fd.append("data", angular.toJson($scope.fdata));
for (i=0; i<$scope.filesArray.length; i++) {
fd.append("file"+i, $scope.filesArray[i]);
};
var config = { headers: {'Content-Type': undefined},
transformRequest: angular.identity
}
return $http.post(url, fd, config);
};
When sending a POST with the FormData API, it is important to set 'Content-Type': undefined. The XHR send method will then detect the FormData object and automatically set the content type header to multipart/form-data with the proper boundary.
I just had this issue. So there are a few approaches. The first is that new browsers support the
var formData = new FormData();
Follow this link to a blog with info about how support is limited to modern browsers but otherwise it totally solves this issue.
Otherwise you can post the form to an iframe using the target attribute.
When you post the form be sure to set the target to an iframe with its display property set to none.
The target is the name of the iframe. (Just so you know.)
I hope this helps
You could upload via $resource by assigning data to params attribute of resource actions like so:
$scope.uploadFile = function(files) {
var fdata = new FormData();
fdata.append("file", files[0]);
$resource('api/post/:id', { id: "#id" }, {
postWithFile: {
method: "POST",
data: fdata,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
}).postWithFile(fdata).$promise.then(function(response){
//successful
},function(error){
//error
});
};
I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!
<input type="file" multiple ng-simple-upload web-api-url="/api/post"
callback-fn="myCallback" />
ng-simple-upload more on Github with an example using Web API.
I just wrote a simple directive (from existing one ofcourse) for a simple uploader in AngularJs.
(The exact jQuery uploader plugin is https://github.com/blueimp/jQuery-File-Upload)
A Simple Uploader using AngularJs (with CORS Implementation)
(Though the server side is for PHP, you can simple change it node also)

Resources