Send XML file as response to ajax - ajax

i have created a xml file from database.
this xml file i need to send as a response from my servlet to ajax.
I have checked various forums and blogs over the web and found that the response xml is created at the time when the servlet is called.
In this case i already have a xml file in my server, i just need to send it as a response to ajax.
Help !!

In your doGet() or doPost() method make sure you set the content-type before writing anything to the response. Like this...
PrintWriter pr = response.getWriter();
response.setContentType("application/xml");
//parse your data to XML
String xml = parseXml(root);
pr.write(xml);
Note: A content-type of "text/xml" should also be valid. Frameworks like JQuery and Prototype support both.

Related

Spring Content 1.2.5 JPA(Postgres) .docx file mutates to zip archive

Saved ".docx" file with mimeType "application/vnd.openxmlformats-officedocument.wordprocessingml.document". But when I access it's endpoint in Spring Content and download it's not exactly Word document, but Zip archive(application/zip). Spring Content 1.2.5 supports ".docx" files, how can we fix it?
Demo project to reproduce issue(.docx file attached):
https://github.com/leonaugust/docx-problem
EDIT
Although I understand that resulting file is docx after all and we can choose to open it as Word document, but is there a way to make it less confusing for customers and return back as ".docx" format? In my case a huge amount of documents will most likely be sent in that format
As you have spring-content-rest on the classpath and use the #StoreRestResource annotation I am assuming that you are using that to fetch your content? Please let me know if that is not the case and I will edit.
There are a couple of annotations that, if present on the entity, the spring content rest post/put endpoints would set for you and that are then used later on by the GET endpoint; #MimeType and #OriginalFileName.
If you add these annotations to your entity and set them appropriately in your post endpoint then:-
#PostMapping
public UUID create(#RequestParam("file") MultipartFile multipartFile) {
File file = new File();
file.setMimeType(multipartFile.getContentType());
store.setContent(file, multipartFile.getResource());
file.setMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
file.setOriginalFileName(multipartFile.getOriginalFilename());
UUID id = repository.save(file).getId();
log.info("id {}", id);
return id;
}
When your client fetches content (again, I assume) via the Spring Content REST endpoint it will set the following headers:
Content-type header
content-dispostion form-data attachment header
on the response.
Both of which will direct the browser app as to handle the content appropriately.
This should allow you to make the following get request from your browser.
curl -H 'Accept: application/vnd.openxmlformats-officedocument.wordprocessingml.document' http://localhost:8080/storage/b9ca6fbe-dede-4a51-b444-9e22b798e922
And it should download the attachments as test.docx
Seperately, I'd be curious to know why you added your own "create" endpoint, rather than using the Spring Data REST/Spring Content REST endpoint. It will do this for you automatically. I assume it is because you do not want to use Spring Data REST?

Upload pdf using ajax and servlet [duplicate]

Can I send a file as multipart by XMLHttpRequest to a servlet?
I am making a form and submitting it as multipart, but somehow I am not getting a response for successfully uploading it. I do not want the page to be refreshed, so it has to take place by Ajax.
That's only possible with the XHR FormData API (previously known being part of as "XHR2" or "XHR Level 2", currently known as "XHR Advanced Features").
Given this HTML,
<input type="file" id="myFileField" name="myFile" />
you can upload it as below:
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "myServletUrl");
xhr.send(formData);
XHR will take care about proper headers and request body encoding and the file will in this example be available on the server side as form-data part with the name myFile.
You need to keep in mind that FormData API is not supported in older browsers. At caniuse.com you can see that it's currently implemented in Chrome 7+, Firefox 3.5+, Safari 5+, Internet Explorer 10+ and Opera 12+.
In case you're using jQuery, then you might be tempted to use its $.val() function as below:
formData.append("myFile", $("#myFileField").val());
But this is incorrect as it doesn't return the whole File object, but merely the file name as String which is utterly useless as it doesn't contain the file contents.
If you don't want to use document.getElementById() for some reason, then use one of the following instead:
formData.append("myFile", $("#myFileField").prop("files")[0]);
formData.append("myFile", $("#myFileField")[0].files[0]);
An alternative is to use the jQuery Form plugin. Your entire form, when written and functioning properly without any line of JavaScript code, will then instantly be ajaxified with just the following line:
$("#formId").ajaxForm(function(response) {
// Handle Ajax response here.
});
It also supports file uploads as well by a hidden iframe trick. See also this jQuery Form documentation for an in-depth explanation. You may only need to change the servlet code to be able to intercept on both normal (synchronous) and Ajax (asynchronous) requests. See also this answer for a concrete example: Simple calculator with JSP/Servlet and Ajax
Either way, the uploaded file should then be available in the doPost() method of a #MultipartConfig servlet as follows:
Part myFile = request.getPart("myFile");
Or if you're still on Servlet 2.5 or older, use Apache Commons FileUpload the usual way. See also this answer for a concrete example: How can I upload files to a server using JSP/Servlet?
It's not possible to send multipart/form-data with XMLHttpRequest (though it is possible in modern browsers, with XHR2. See BalusC's answer).
A common way to achieve what you want is to use a regular form, but in an iframe instead. This way, only the iframe is refreshed on upload.

Why is XML response returned by default in Web API?

When nothing is specified in "accept" header in the request, why is XML response returned by default in Web API? I mean is there anything which makes the framework to do so?
XmlMediaTypeFormatter is the default formatter, as this is the order in which they are found in the 'Formatters' collection of the HttpConfiguration object
https://stackoverflow.com/a/20192316/1538039
You can change the behaviour here by clearing down and only adding in a Jsonformatter, e.g.
configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());
The link to StrathWeb contains additional information

Load data from ajax request (json) on startup in AngularJs

I have this simple page that just needs to show contents that is loaded from an external url (ajax request, response in json format)
I should say I'm a AngularJS newbie.
I've googled a bunch and found different ways of doing this and couldn't manage to determine which is the correct/simple/up-to-date way to achieve this.
My 2 challenges -
Making the AJAX request run on startup (I can load the page before that happens and just load the contents one the ajax request finishes. Maybe show a 'Loading..' indicator)
Doing a ajax request correctly.
Here is my attempt. I know that the ajax request is never made because its not setup correctly.
You are getting into .error function:
http://jsbin.com/oDUsuVA/3/edit
For jsonp your response should be something like:
callback([
{
"title":"License Title 1",
"licenseUrl":"http://cnn.com",
"licenseText": " test"
}]);
Edit:
You can simply do .get() request too, but if you had to use jsonp request interface, you would have to correct response.
A Jsonp request always wraps the logic into a json callback wrapper function.
I just did $http.get instead of your $http.jsonp and it did work for me.

Retrieving XML data from a ReST service across domains with Dojo

I am trying to write a browser-based Javascript client for a ReST application which responds with XML (so it seems JSONP is out of the questions).
I am trying to retrieve the data using dojo.io.script.get but the parameter that is passed to the callback function is an object from which it seems I cannot retrieve the XML data of the response.
dojo.io.script.get({url:"http://enterpriseapp.enterprisedomain/path/to/rest/collection",
load:function (data) {
// 'data' does not contain the actual response (which is XML)
}
});
What is the correct way to retrieve this data?
The dojo.io.script.get method will inject a <script> from the specified web address. The data content from this script will be passed to your load function; hence, the content must validate as Javascript. You can't load XML into a script tag.
If you want to load XML, you'll need to use dojo.xhrGet; however, this will not allow requests to 3rd party urls. The advantage of using dojo.io.script.get is that you can use different origin address' than the page loading them.
dojo.xhrGet({
handleAs: "xml",
load: function(dom){
// do something with the DOM XML object
},
error: function(error){
}
});
See: dojo.xhrGet Documentation
If you are trying to load the XML from another website it's a bit of a dead-end. You can use the Access-Control-Allow-Origin header if you have access to the sending server.
Another solution that I have used is to write a proxy script (in PHP or other server language) to mirror the XML on the correct domain. You'll need to be careful if you do this to include good checks so that your server code is not abused by someone for proxying.
See the following Stackoverflow conversation for more about Access-Control-Allow-Origin:
jQuery XML REST Access-Control-Allow-Origin

Resources