How to get a file from Content-Disposition in java? - java

i am trying to post a file form my jsp and wnat to get on my servlet page but i ma not geting what ever code i did i mention below
index.jsp
</form>
jquery :
$.ajax({
url: '/test/picctureUpload',
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(response) {
// console.log(response);
var dataString = jQuery.parseJSON(response);
console.log(dataString.path);
}
});
i have written following code in server side:
Part part = request.getPart("files"); // input type=file name=xxx
log.debug("Get content type==>"+part.getContentType());
log.debug("Get file name==>"+part.getName());
i am getting java.lang.NullPointerException here, how can i solve this issue?
Thanks
form data post:
-----------------------------9962829018914
Content-Disposition: form-data; name="file"; filename="297994_231238580266568_1872824895_n.jpg"
Content-Type: image/jpeg

Check the java doc here: http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
You will see a detailed example of upload servlet.

Related

JQuery AJAX doesn't get to success call back function

Here is my jQuery Ajax code
$(document).ready(function() {
$("#submitService").click(function(){
alert("Before ajax");
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk",
headers: {"accept": "application/json"},
success: function (dataItem) {
alert("Success..");
},
complete: function (dataItem) {
alert("Completed");
},
error: function (dataItem) {
alert("Error in making engine call."+dataItem);
}
});
alert("After ajax");
}); //click()
});
When my button is clicked it enters to [complete] and [error] call back methods but NOT to "success" call back method. How can I see what the error is?
I tried to curl the same statement and I get a valid response:
curl "http://api.openweathermap.org/data/2.5/weather?q=London,uk" -H "accept: application/json"
I'm using jQuery 1.7.2
<script type="text/javascript" src='<spring:url value="/resources/jquery/js/jquery-1.7.2.min.js"/>'></script>
In FireBug it shows that request with 200 OK, but no response body. But I see response body when I do it via curl.
What could be the issue?
Thanks
I guess, it is URL encode problem. Replace comma , with encode %2C
url: "http://api.openweathermap.org/data/2.5/weather?q=London%2Cuk"
Cancel the click event
$("#submitService").click(function(e){
e.preventDeault();
...
and let jQuery do the proper encoding of the URL
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather",
data: {q : "London,uk" },
and hopefully the service and your browser both support CORS since this is a Same Origin Policy issue.
Did you notice there are no Allow-Access-Origin in Api call?
I got this on chrome
XMLHttpRequest cannot load
http://api.openweathermap.org/data/2.5/weather?q=London,uk. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://jquery.com' is therefore not allowed access.
I think you have a cross site scripting issue.
change application/json to application/x-www-form-urlencoded

Parsing with Jsoup, only gets default value

I'm parsing a webpage with Jsoup which so far is going good, except that when I parse, I get the data that's the 'default text', the text displayed right before a javascript changes the value.
There's
<span id="p1name" class="redtext">Player 1</span>
which I can parse with
Element player1Div = doc.getElementById("p1name");
p1name = player1Div.text();
player1.setText(p1name);
Then there's a script on the website
<script>
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
type: 'get',
url: '../data.json',
data: '',
dataType: "json",
success: function(data) {
player1name = data['p1name'];
$("#p1name").text(player1name);
</script>
which changes the element's text. So I thought I could just run the java code again and get the new text, but that won't work as I keep getting "Player 1" (whereas I'm sure it should display a different string)
What are my options? How do I solve this?
JSoup can't solve your problem. All Jsoup knows is parse and extract the data.
As the desired text is not part of the html during the parsing it can't be extracted from the Document
All you can do is, issue a new request to ../data.json and fetch the data. Provided, you know that url before fetching the content.

How to convert bytearray to img tag?

I have a service which returns byte array of png image , I want to render it on my jsp page .
I am making ajax call to get the image.
$.ajax({
type: "GET",
cache: false,
async: false,
url: '<spring:url value="/service/org/flk/2"/>',
success: function(msg) {
You will need to stream base64 encoded data in response and then you can do it like
$("#someDivId").html('<img src="data:image/png;base64,'+response + '"/>');
where response is the base64 encoded image data

Rendering JSONP in HTML format on Java Servlet response

I am having a problem. I have a form submit that uses jQuery JSONP to make a call BACK to my servlet. This code is embedded in another domain, hence the usage.
Here is my form submit AJAX:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js' type='text/javascript'></script>
<script language='Javascript' type='text/javascript'>
$(\"#form1\").submit(function(event) {
event.preventDefault();
var $form = $(this),
choice2 = $form.find( 'input[name=\"personChoice\"]' ).val(),
url = $form.attr( 'action' ),
    $.ajax({
data: {choice:choice2},
        url: url,
        dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'updatePage'
});
});
function updatePage(renderHTML) {
alert(renderHTML);
}
</script>
I can confirm in my Java servlet that the request.getParameter("callback") is populated with updatePage. What I need to do is send back a response in JSONP format within the Java Servlet. How does one do that? I have something really simple like this at the moment:
Java Servlet code:
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();
String renderHTML = "{ renderHTML = 'Successful'}";
out.println(renderHTML);
I also tried JSON content type response, the alert in my javascript updatePage doesn't get called.
What is the trick with Java servlet's and response back on a jsonpCallback???
A JSONP response must be wrapped inside a function call which is specified in request with callback.
Something like
callback({ renderHTML = 'Successful'});
This should usually be taken care at a filter.
The jsonpCallback property is not what you think it is. It's a string (or a function returning a string) which jquery will use as part of the request URL. You can set it to false if you don't need that functionality. See the docs
You should use the 'success' property to set the response handler.
Something like this:
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: false,
error: function(xhr, status, error) {
alert("error");
},
success: updatePage
});
Also, the best content-type to use for JSONP is application/javascript.
Hope that helps.

send parameter to Java Server Pages (JSP) using jQuery

I want to send different parameters to JSP. Is it possible to send multiple parameter to JSP in jQuery? Because jQuery is client side and JSP is server side.
Update me!
You can make an ajax request passing parameters
For example:
$.ajax({
type: "POST",
url: "userNameCheck.jsp",
data: { username: "John"}
}).done(function( msg ) {
alert( msg );
//do other processing
});
See
jQuery.ajax
Simplest case: you want to open some page with javascript (jQuery). In this case you can send parameters in request to page:
document.location.href = "http://yourdomain.com/yourpage.jsp?paramName=" + paramValue;
If you need to send data without page reloading use ajax as Jigar say.
You can do like this:
$.ajax({
type: "POST",
url: "yoursite.com",
contentType: "application/json; charset=utf-8",
data: {param1: value1 , param2: "value2", param3: "value3"},
dataType: "json",
success: Succeess,
error: Failed
});

Categories