I am working on a jsp application and I have a download zip file feature
I have done
#RequestMapping(value = {"/retrieve"}, method = RequestMethod.POST)
public void logDownload(#RequestBody ResponseDto responseDto, Model model, HttpServletResponse response) throws ServletException, IOException {
Byte[] arraObj=downloadService.getdownloadFile();
response.setContentType("application/octate-stream");
response.setHeader("Content-Disposition","attachment;filename=user.zip",
response.getOutputStream().write(arraObj);
}
I am making a ajax call for this controller
JSP Side code
$.ajax({
type: 'POST',
url: "${pageContext.request.contextPath}/retrieve",
headers: { "X-CSRF-TOKEN": token },
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(retrieveDto),
success: function (res) {
window.location = "${pageContext.request.contextPath}/result";
},
error: function (e) {
// window.location="${pageContext.request.contextPath}/result";
console.log("There was an error with your request..." + JSON.stringify(e));
}
});
I am unable to download the file
Can someone tell me how to fix this issue
Related
I am working on a jsp file upload using ajax call and I am able to hit the java controller in the HttpServletRequest I see the multipart file received but when I do request.getInputStream.readAllBytes(), I get an empty byte array
The ajax call in javascript
function saveFileUpload() {
var data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}
}
In Java controller
#RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
public void fileUpload (
HttpServletRequest request, HttpServletResponse response){
byte[] arr = request.getInputStream().readAllBytes();
System.out.println(arr.length);
}
The above code prints arr.length as 0. Can someone tell me the reason for this issue?
I assume that you are using Springboot and your application supports multipart/form-data. After version 3.0 the Servlet API natively support it.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void fileUpload(#RequestParam("file") MultipartFile file) throws IOException
{
if (!file.isEmpty())
{
byte[] bytes = file.getBytes();
// and so on
}
}
JQuery's Ajax:
function saveFileUpload() {
let data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}
Hi I have the following ajax call in my client side.
var arr = JSON.stringify(JSON_Array);
$.ajax({
url: 'http://localhost:8080/',
type: 'POST',
data: arr,
dataType: 'text',
contentType: 'application/json',
success: function () {
console.log("Success!");
},
error: function() {
console.log("error");
},
});
Server side:
#Controller
public class Controller{
#RequestMapping("/")
public String start() {
System.out.println("works"); //prints
return "index";
}
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = "text/plain")
public void process(#RequestBody String payload) throws Exception {
System.out.println("payload " + payload); //does not print
}
}
The ajax call is successfully sent off, however nothing is received in the server side. The process method is not being used. I am not too sure why. Help would be appreciated.
edit:
Changes made following #Toofy's comment
In Ajax call:
dataType: 'text',
contentType: "text/plain;",
process method kept the same.
I also tried changing the Ajax call to the following
dataType: 'json',
contentType: "application/json;",
and the server side changes:
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json")
public void process(#RequestBody String payload) throws Exception {
System.out.println("payload " + payload);
}
in both these cases the ajax calls stop working
Got it to work by doing the following:
In Ajax call I got rid of dataType
$.ajax({
url: 'http://localhost:8080/',
type: 'POST',
data: arr,
contentType: "application/json; charset=utf-8",
});
In the server side I changed the process method to
#RequestMapping(value = "/", method = RequestMethod.POST)
#ResponseBody
public void process(#RequestBody String payload) throws Exception {
System.out.println(payload);
}
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
here's my js code :
function sendMP3ViaAJAX(MP3File) {
console.log(MP3File.name); //file is present, as I can get its name
$.ajax({type: "POST",
url: "saveMP3",
enctype: 'multipart/form-data',
processData: false,
data: {'mp3File': MP3File},
success: function (text)
{
response = text;
},
complete: function () {
$("#retourAJAX").html("blah blah");
}
});
}
but if I debug my Project
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("MP3FILE"); //request.parts is null...
(constant CHAMP_FICHIER equals the one defined in AJAX call, i.e. mp3File ...) Do you know what's missing ? As I already have dynamically loaded content on the page, I don't want the default HTML POST submit behavior to happen...
I am triyng to do a simple thing, with ajax, send a request (using a GET, or POST).
I will be sending 2 parameters in a json format , and I just want to get them back and send a response, still, I always get an error 400 and others that I dont know whats wrong, any idea how?
I started based on this article: http://fruzenshtein.com/spring-mvc-ajax-jquery/
I am using spring mvc.
So far I have this:
$(".update_agent").live('click', function(){
var agent = { "agentId" : agentID, "hostAGent" : hostID};
//send ajax
$.ajax({
url: url,
data: JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
})
and at my java controller I have this
#RequestMapping(value = "/update", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int updateAgent(HttpServletRequest req, HttpServletResponse res) throws IOException{
req.getParameterValues("agentId");
return AGENT_UPDATE_SUCCESS;
}
But I cant get it back, have no idea how to make the request of the params, any idea?
Thanks.
=====================UPDATE============================
Ive changed the code and this how it looks like...
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: 'POST',
url: url,
data: JSON.stringify(agent),
dataType: 'json',
success:function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
And at my controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Integer updateAgent(#RequestBody String param) throws IOException{
System.out.println(param);
//do something...
return 1;
}
the problem is that I am getting an error 415, unsupported media type, any advice?
GET-request can not have 'data'-field. You need to send your data as part of the url:
$.ajax({
url: url + "?agent=" + JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
now you can get the data in your controller as:
#ResponseBody public ResponseEntity<String> updateAgent(#RequestParam(value = "agent") String agentJson){
...
}
or you can send a POST-request. With a POST-request you can send your data as requestBody:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody String agentJson){
...
}
EDIT:
create a new Agent-class:
public class Agent {
private long agentId;
private long hostAgent;
...
getter and setter
...
}
now update the controller to:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody Agent agent){
System.out.println(agent.getAgentId());
}
and change the "Content-Type" of ajax-call to "application/json".
EDIT2:
change your ajax-call data to:
data: { agentId: agentID, hostAgent : hostAgentID} ,
or even
data: agent ,
Don't forget to change "hostAGent" to "hostAgent" in your agent object, or you will get 400!!!
now ajax will send the data as request parameters, you can get the data in your controller by:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestParam(value = "agentId") long agentId, #RequestParam(value = "hostAgent") long hostAgentId){
System.out.println(agentId);
}