I am uploading image file using ng-file-upload for image upload. using the example given, I encountered access-control header error.
vm.uploadPic = function(file) {
file.upload = Upload.upload({
url: 'http://localhost:8000/api/v1/quotes/quoteitem/image/upload',
data: {quote_item_id: vm.quote_item_id, filename: file}
});
}
This gives error
XMLHttpRequest cannot load http://localhost:8000/api/v1/quotes/quoteitem/image/upload. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I don't need any header request while uploading image in postman so, I removed header.
vm.uploadPic = function(file) {
file.upload = Upload.upload({
url: domain+'/api/v1/quotes/quoteitem/image/upload',
data: {quote_item_id: vm.quote_item_id, filename: file},
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
headers['Content-type']=undefined;
return headers;
}
});
}
This gives
TypeError: data.hasOwnProperty is not a function
at ng-file-upload.js:310
at angular.js:10484
at forEach (angular.js:322)
at transformData (angular.js:10483)
at $get.serverRequest (angular.js:11211)
at processQueue (angular.js:15961)
at angular.js:15977
at Scope.$get.Scope.$eval (angular.js:17229)
at Scope.$get.Scope.$digest (angular.js:17045)
at Scope.$get.Scope.$apply (angular.js:17337)
I am stuck in this for quite a time now. I have tested in server side and it works fine in postman. Any help would be wonderful.
The problem is that you are uploading from the site at port 3000 to an endpoint at port 8000. These are considered separate origins, so the browser's security features are kicking in. You either need to get them on the same origin, or add the 'Access-Control-Allow-Origin' header to the server-side response of the upload endpoint.
Please try these one
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
alert("success");
})
.error(function(data){
alert("error");
});
};
}]);
myApp.controller('fupController', ['$scope', 'fileUpload', '$http', function($scope, fileUpload, $http){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is '+ file );
console.dir(file);
var uploadUrl = 'http://localhost:8000/api/v1/quotes/quoteitem/image/upload';
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
Try this
<form method="post" enctype="multipart/form-data" ng-controller="commentCtrl" name="form">
<img src="source/assets/images/icons/icofileattached.png" class="attachmentpng-height" ngf-select="uploadFiles($file)" ng-model="files"/>
<md-button type="submit" class="md-raised custom-submit-button" ng-click="MakeComments()"> SUBMIT </md-button>
</form>
$scope.uploadFiles = function(file) {
console.log(file);
$scope.fileData = file;
var fd = new FormData();
fd.append('file', file);
Restangular.one('/api/files/end points').withHttpConfig({transformRequest: angular.identity})
.customPOST(fd, '', undefined, {'Content-Type': undefined})
};
Related
I am uploading a file using angular and node.js API.
I am following this link to upload a file.
In this tutorial we need to set header headers: {'Content-Type': undefined}
On other hand I need to set headers value for authentication token . For that I am setting default headers value like as $http.defaults.headers.common.Authorization = $cookieStore.get('token');
Now when I uploading a file then a error is shwoing i.e
Error: Can't set headers after they are sent.
Now please let me know how can I resolve this..
Or any solution to achieve this.
Thanks
Below is the Service and Controller for file upload
app.service('fileUpload', ['$http','$cookieStore', function ($http, $cookieStore) {
this.uploadFileToUrl = function(file, uploadUrl){
var token = $cookieStore.get('token') ;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {transformRequest: angular.identity,headers: {'Content-Type': undefined} })
.success(function(res){
})
.error(function(){
});
}
}]);
app.controller('csvCtrl', function($scope, fileUpload){
$scope.importcsv=function(){
var file=$scope.myFile;
var uploadUrl="/api/parsecsv";
fileUpload.uploadFileToUrl(file, uploadUrl);
}
});
This should get you to the point of being able to apply the header:
app.service('fileUpload', ['$http', '$cookieStore', function ($http, $cookieStore) {
this.uploadFileToUrl = function (file, uploadUrl) {
var token = $cookieStore.get('token');
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd,
{
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Authorization': token
}
})
.success(function (res) {
})
.error(function () {
});
}
}]);
Once you get that working, you can set the default headers with an interceptor.
In a web application made with AngularJs there is a page where the user can upload a file. But I have some problem.
This is the Factory that makes the upload:
angular.module('app').factory('FileUpload', ['$http', function($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
If I try to upload a file, console gives me this error:
"Error: [$injector:undef] Provider 'FileUpload' must return a value from $get factory method.
This is the function in the Controller:
$scope.uploadFile = function(){
var userId = $stateParams.userId;
var fileType = $stateParams.fileType;
var file = $scope.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = 'my_url';
FileUpload.uploadFileToUrl(file, uploadUrl);
};
The pattern you're using should use service not factory. With factory you want to return the new'd up instance, with service you just provide the function.
angular.module('app').service('FileUpload',...
I have following API in jersey for file upload :
#Path("/image/upload")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public Response Imageupload(
#QueryParam("filename") String filename,
#FormDataParam("file") InputStream fileInputString,
#Context ContainerRequestContext crc)
throws ConnectException, SQLException, InvalidCredentialsException, IOException, GeneralException {
}
and I am using angular js for uploading file :
_myApp.service('fileUpload', ['$rootScope', '$http', function($rootScope, $http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + $rootScope.token
},
params:{
'filename':file.name
}
})
.success(function() {
})
.error(function() {
});
}
}]);
_myApp.controller('uploadImageController', ['$rootScope', '$scope', '$http', 'fileUpload', function($rootScope, $scope, $http, fileUpload) {
$rootScope.show = true;
$scope.upload = function() {
//$scope.fileObject is the File I am trying to upload
console.log($scope.fileObject);
var file = $scope.fileObject;
var uploadUrl = "http://xx.xx.xx.xx:8080/ImageAPIS/image/upload";
fileUpload.uploadFileToUrl(file, uploadUrl);
}
I am getting the following error :
400 Bad request : The request sent by the client was syntactically incorrect.
Am I posting the request in wrong Angular standard? I can see the payload being sent, What mismatch is between the Jersey and my Angular request sent?
I have refereed the following File upload code -http://www.tutorialspoint.com/angularjs/angularjs_upload_file.htm
I'm working on a Grails (2.3.7) application with AngularJS. I've to upload files in my application. Since the front end is managed by Angular , I'm uploading my file from Angular controller. I've gone through This
and this discussions , and tried to upload as follows.
My file uploader is
<input type="file" ng-file-select="onFileSelect($files)">
Angular controller is
myapp.controller('createWebController',['$scope','$http','$upload',function($scope,$http,$upload){
$scope.onFileSelect = function($files) {
var file = $files[0];
console.log(file)
$upload.upload({
url: 'UploadLogo/upload', //upload.php script, node.js route, or servlet url
file: file,
method: 'POST' ,
fileFormDataName: "myFile",
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
})
.error(function(data){ console.log(data)})
;
};
}])
on the server , I'm using this service and the upload handler code is
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.MultipartFile
import org.codehaus.groovy.grails.web.context.ServletContextHolder
class UploadLogoController {
FileUploadService fileUploadService
def upload() {
def avatarImage = request.getFile('file')
if (!avatarImage.isEmpty())
{
userInstance.avatar = fileUploadService.uploadFile(avatarImage, "logo.png", "~/Desktop/upload")
render "ok"
}
else
{
render "Empty"
}
}
}
But the problem is I'm getting a 500 (Internal Server Error) from grails. The file is not being uploaded.
also getting response as Cannot invoke method isEmpty() on null object
Which means the file has not been sent to the server. Whats the problem here.. Please help..
Try this way. You could create a custom directive for the file upload control
myapp.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}])
and in your html use <input type="file" ng-file-model="myFile" />
Then you could create a custom service to do the file upload. Note that its not necessary to create service but it can easily reuse in later file uploads just by injecting the service.
myapp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl,filename){
var fd = new FormData();
fd.append('file', file);
fd.append('filename', filename);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
console.log(data)
})
.error(function(data){ console.log(data)
});
};}]);
The uploadFileToUrl takes 3 arguments , the file itself , the URL to upload and the file name to be saved as.(You can customize this as you wish) . Use the $http.post to post data.
Finally in your controller , include this
var file = $scope.myFile;
var filename = 'YourFileName'
var uploadUrl = '/UploadLogo/upload' // don't forget to include the leading /
fileUpload.uploadFileToUrl(file, uploadUrl,filename);
Sorry i havent used file uploads in node.js before
Currently i cam using angular service that uses FormData and submits a $http post request to php and there it is uploaded with move_uploaded_file() that is working fine
Angular .js code
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "upload.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
html
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
How can i get this into node.js express route?
i have read other questions on stack overflow but i cant quite get it that were will the data be going in res.body? or res.files and how to finnaly upload them
my undesrtandings about it is that it will be something like this
routes.post("/upload",function(req,res,next){
console.log(req.Files);
console.log(req.body);
});