Getting exception in JQuery file uploader - java

I am new to JQuery file uploader and I am implementing some part of that. When I select an image from JQuery file uploader, a call goes to server side (SpringController) but the API returns:
406 Not Acceptable
this my call to server:
$(this).fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: uploadSettings.upload_url,
type: 'POST',
maxNumberOfFiles: uploadSettings.maxNumberOfFiles,
maxFileSize: uploadSettings.maxFileSize,
acceptFileTypes: uploadSettings.fileSelection,
sequentialUploads: true,
paramName:'uploadfiles[]',
dataType: 'text'
});
and my Java Controller code is as:
#RequestMapping(value = { "/user/fileuploader" }, method = RequestMethod.POST,
produces = "text/plain")
#ResponseBody public String uploadFileHandler(
#RequestParam("uploadfiles[]") MultipartFile[] file,
HttpServletRequest request, HttpServletResponse response) {
Any advice?

Here is a project that uses a very similar stack to JHipster (I'm the author of both projects), and which does uploading with the same JQuery plugin:
https://github.com/ippontech/tatami/blob/master/src/main/java/fr/ippon/tatami/web/fileupload/FileController.java#L193
As you can see my return object is different. You can copy my code from:
https://github.com/ippontech/tatami/tree/master/src/main/java/fr/ippon/tatami/web/fileupload

Related

Get the file name for a document attached using AJAX on the JSP page

I have a JSP form where in one of the field I am uploading a document, say a notepad using an AJAX call and the upload is happening in a UNIX path. Now I need to see the name of the attached document on the jsp once the upload is successful. Please let me know how can I do it.
Ajax Call:
$.ajax({
type : 'POST',
url : '/test/actionToController/',
data: new FormData(document.getElementById("formNameInJSP")),
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
async: false,
success : function(result) {
},
error : function(result) {
console.log('ohh.. something happened in Document Upload');
}
});
Controller:
#RequestMapping(value = "/actionToController", headers=("content-
type=multipart/*"), method = RequestMethod.POST)
public String actionToController(#RequestParam("myFile")
CommonsMultipartFile[] fileUpload, HttpSession session)
throws JsonGenerationException, JsonMappingException, IOException {
/* Upload Code removed from here, its working fine */
docName = notepadTest.txt;
return "docName";
}
docName here has the name of the file which we need to see in the JSP page.
Thanks

Getting 400 BAD REQUEST when uploading a blob to JAVA server Jersey API

I'm trying to upload a cropped image sending it as a blob and getting an 400 http error.
When checking it carefully, I've noticed the following exception:
java.lang.IllegalStateException: Entity input stream has already been closed.
The JavaScript code:
var fd = new FormData();
fd.append("pic", cblob); //append the blob
$.ajax("/wsbasestructure/ws/users/test", {
data: fd,
type: "PUT",
processData: false,
contentType: false,
success: function (data) {
}
});
The Java code:
#PUT
#Path("/test")
public String updatePic(#FormDataParam("pic") InputStream file){
System.out.println(file);
return null;
}
What am I missing here?
Thank you for your time.
See :
http://api.jquery.com/jquery.ajax/
https://jersey.java.net/nonav/apidocs/1.0.3/contribs/jersey-multipart/com/sun/jersey/multipart/FormDataParam.html
You need your form to be a multipart/form-data content type.
So you need :
contentType: multipart/form-data
And maybe you should change the Web Service.
Try this :
#PUT
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/test")
public String updatePic(
#FormDataParam("pic") InputStream file,
#FormDataParam("pic") FormDataContentDisposition fileDisposition) {
...
}
Source: Jersey doc

Spring MultipartFiles duplicates file in mixed multipart

I have UI code like this
.factory('Service', function ($http, $resource, BASE_PATH) {
function sendResponse (code, responses) {
return $http({
method: 'POST',
url: "/test",
headers: {'Content-Type': undefined},
transformRequest: function (data) {
var formData = new FormData();
formData.append("dec", new Blob([angular.toJson(data.dec)], {type: 'application/json'}));
angular.forEach(data.files, file => {
formData.append("file", file);
});
return formData;
},
data: {dec: responses.dec, files: responses.files}
});`enter code here`
}
and here is controller part
#RequestMapping(value = "/test", method = POST)
public ResponseEntity<List<Test>> save(#RequestPart(value = "file", required = false) MultipartFile[] multipartFiles,
#RequestPart(value = "dec") List<Decision> dec) {
return save(multipartFiles, dec);
}
The problem is, MultipartFile has duplicated files. For example I attach one "test.txt" but, I see two "test.txt" files in controller while debugging.
Is there any way to solve this issue?
I was using zuul server in between as API gatway. I found there is a bug in old version of zuul which duplicated one part of multipart object.
The solution can be referred here
github.com/spring-cloud/spring-cloud-netflix/issues/1171

Android app submit throws Request method 'GET' not supported

I am new to app world and started building Android app using phonegap for my already available service which serves for my web users. i have my services build on java, spring mvc, and my controllers are capable of receiving json objects.
so kept that in mind. i have created basic login page with login button and i was trying to hit my backend services. i have below code
$('#login_btn').click(function() {
$.ajax({
url: "http://localhost:8080/myweb/user/signin",
type: "post",
crossDomain: true,
cache: false,
data: "userName=" + $("#username_txt").val() + '&password=' + $("#password_txt").val(),
dataType: "jsonp",
async: true,
success: function(data) {
alert("ok");
},
error : function(data){
alert("not ok");
}
});
my controller method accepts POST request, when i hit login button, i see my service giving me error as
HttpRequestMethodNotSupportedException: Request method 'GET' not
supported
and my error block getting executed.i dont what i am doing wrong here, thanks for your answers
EDIT-
my server side controller code
#RequestMapping(value = "/signin", method = RequestMethod.POST)
public #ResponseBody
ModelMap loginUser(#RequestParam(value = "userName") String userName, #RequestParam(value = "password") String password, HttpSession session, HttpServletRequest request) {}

Pass JSON as Java Class to Spring Controller by GET

I have the following code that works:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassPost(#RequestBody ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and the corresponding ajax call by post:
$.ajax({
url: '/jsonasclass/',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
}),
contentType: 'application/json',
mimeType: 'application/json',
success: _callBack,
error: _errorCallback
});
Now I want to achieve the same thing, but I want to do it by GET. Anyone knows how?
I have tried changing POST to GET (in both controller and ajax call) but it did not work.
The error I get: description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thanks to RaulRene's comment here is how you would do it.
get rid of #RequestBody from the controller and change method to get.
send the properties of the class in the controller as browser variables and spring will automatically map them to the class.
Here is the solution:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassGet(ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and corresponding ajax:
$.ajax({
url:'/jsonasclass/',
type: 'GET',
data: {
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
},
success: _callBack,
error: _errorCallback
});

Categories