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
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.
Actually, I am uploading image using service, image uploaded successfully, but I want responded data to the function in controller.
Controller:
adminApp.controller('imageController', ['$scope', 'fileUpload', 'Images',function ($scope, fileUpload, Images) {
$scope.uploadFile = function (data) {
console.log(data);
var file = data.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/image";
fileUpload.uploadFileToUrl(file, data, uploadUrl);
// $scope.images.push();
};
}]);
Service:
adminApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, data, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
})
.error(function () {
});
}
}]);
laravel (backhand):
public function store(Request $request)
{
$image = $request->file('file');
$image = $this->imageRepository->makeImage($image);
return $image;
}
I function in service return responded data from backhand to controller, so I can push the value to $scope.images in controllers function.
You can take advantage of angular $q here.
Updated Service Function
this.uploadFileToUrl = function (file, data, uploadUrl) {
var defer = $q.defer();
var fd = new FormData();
fd.append('file', file);
fd.append('owner_id', data.owner_id);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function (data) {
// return data;
defer.resolve(data);
})
.error(function (error) {
defer.reject(error);
});
}
return defer.promise;
}]);
In your controller, you can use the function as
fileUpload.uploadFileToUrl(file, data, uploadUrl).then(function(response){
//response contains your data form service
}).catch(function(error){
// error variable contains error data from service.
});
the code is not tested.. but it should work or very close.
I'm trying to get a file using $http, I tested my code in another application and it's working well but in my application I get this error:
this is my code:
app.controller("directoryCtrl", ["$scope", "$http", "Restangular", "langFctr", "$translate", function($scope, $http, Restangular, langFctr, $translate) {
$scope.uploadFile = function(files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post("/input", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).then(function successCallback(response) {
console.log("ok");
}, function errorCallback(response) {
console.log(response);
});
};
}]);
I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.
My angular controller is
app1.controller('kyc_controller', ['$scope', '$http', function($scope, $http)
{
$scope.uploadFile = function(){
var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
$http({
method : 'POST',
url: '/GngService/api/GoNoGo/upload_file',
params : {'filename':'pancard'},
data : fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + JSON.stringify(data));
});
};
}]);
and my server side api method is
#POST
#Path("/upload_file")
#Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response upload(#FormDataParam("file") InputStream ins, #FormDataParam("filename") String filename, #FormDataParam("file") FormDataContentDisposition contentDispositionHeader ) throws IOException {
System.out.println(filename);
BufferedImage image = ImageIO.read(ins);
// ImageIO.write(image, "jpg", new File("/../../fileName"));
String result = "{'status' : 'ok'}";
String json = new Gson().toJson(result);
return Response.ok(json.toString(), MediaType.APPLICATION_JSON).build();
}
It shows Unsupported media type...please help me to upload images....thanks in advance