Error while using Uploadify - java

I am new to Jquery, I have a problem regarding uploading the files using Uploadify. Iam trying to send a file to the Java Servlet which uploads the file using apache commons.
But while executing the code, it is not all going to servlet. I actually took this sample example from web and trying it. Can anyone advice what am i missing? I am pasting the client code below:
My understand is "script" parameter in uploadify function will call the servlet. so, I have written my Servlet name in script parameter.
Please advice me how to proceed further.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SimpleFileUpload</title>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" href="css/uploadify.css" type="text/css" media="screen"/>
<script type="text/javascript">
$(function() {
$('#file_upload').uploadify({
'uploader' : 'swf/uploadify.swf',
'script' : 'fileupload',
'cancelImg' : 'img/cancel.png',
'multi' : false
});
});
</script>
</head>
<body>
<h1>Simple File Upload</h1>
<h3>Multiple file upload made easy</h3>
<div id="file_upload"></div>
<br/>
<input type="button" value="Clear Queue" onclick="$('#file_upload').uploadifyClearQueue();"/>
<input type="button" value="Submit Queue" onclick="$('#file_upload').uploadifyUpload();"/>
</body>
and my servlet code is
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)){
// Parse the HTTP request...
try {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator itr = fileItemsList.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
// check if the current item is a form field or an uploaded file
if(item.isFormField()) {
// get the name of the field
String fieldName = item.getFieldName();
// if it is name, we can set it in request to thank the user
if(fieldName.equals("name"))
request.setAttribute("msg", "Thank You: " + item.getString());
} else {
File fullFile = new File(item.getName());
String filename = item.getName();
File targetdir = new File("E:/");
File savedFile = new File(targetdir,fullFile.getName());
item.write(savedFile);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
} //end servletFileUpload
Thanks,

I just used swfupload... Using fiddler i was seeing my basic example only was submitting 1 file with uploadify so i gave up on it.

Related

How to call a javascript function after submit Form to Servlet?

I try to make countdown clock, but I can not call a javascript function by <script type="text/javascript">...</script> inside <c:if>...</c:if>. Can you help me solve this problem or give some solution to make countdown in jsp file?
demo.jsp: countdonw() function not called
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo Page</title>
</head>
<body>
<form action="demo" method="POST">
Time: <input type="text" id="input-time" name="inputTime">
<input type="submit" value="Start">
</form>
<c:if test="${timeRemain!= null}">
<input type="hidden" id="time-remain" value="${timeRemain}">
<p>Time Remaining: <span id="display-time"></span></p> //this line work
<script type="text/javascript">
countDown(); //not call this function
</script>
</c:if>
</body>
<script type="text/javascript">
async function countDown() {
var timeRemain = document.getElementById("time-remain").value;
alert(timeRemain);
}
</script>
</html>
demo.java servlet just send timeRemain to jsp file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String inputTime = request.getParameter("inputTime");
request.setAttribute("timeRemain", Integer.parseInt(inputTime));
request.getRequestDispatcher("demo.jsp").forward(request, response);
}
Try This:
<script type="text/javascript"> //oustide <c:if> tag
var timeRemain = document.getElementById("time-remain").value;
if(timeRemain.length>0 && timeRemain !== "undefined")
{
countDown();
}
</script>
Note: Better option would be to AJAX over here
Refer: https://www.javatpoint.com/ajax-tutorial

Why my web application does not redirect correctly?

I am trying to pass an attribute from a java servlet to jsp and write this attribute on jsp file. However it does not redirect to jsp file url but it writes the content of the jsp file. Here is my related codes:
Control.java:
#WebServlet("/Control")
public class Control extends HttpServlet{
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
Here, browser stays on http://localhost:8080/Control but it writes the content of Home.jsp file which is just a java web token result string.
2) My second question is when I tryed to store this jwt result string in browser local storage and then write it in jsp file in order to check if it stored in browser or not. But it does not prints anything. To do this, I just changed the Home.jsp file as follow:
(I took both of the code snippets from here)
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
Another try:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
Where am I doing wrong?
1) When you use RequestDispatcher.forward(request,response), your servlet will still have control but your jsp page will be loaded so this is nothing to worry about.
If you want your browser URL to show your JSP page URL, do response.sendRedirect("URL TO LOAD");
2)Since you are using JSP, try accessing the request variables like below and print it
<% String jwt = (String) request.getAttribute("jwt");%>
We need to set it as
localStorage.setItem('jwt', <%=jwt%>);

Unable to log Json response in Ajax from servlet Java?

I am trying to log a json response from my servlet in my ajax call. Now, here is the thing, I tried experimenting with logging string response in my ajax and things seemed to work fine but then I try to log the json response, I see nothing in my console. I am wondering if I am missing out on something.I tried calling my servlet from POSTMAN and I got the proper json response.
HomeServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<!--
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit"> -->
<br>
<input type="submit" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
console.log("response",responseText);
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
You will need to write a callback, this will be fired when your ajax call completes, try like below
function success(data) {
console.log( data );
}
function failure(err) {
console.error( err );
}
ajax( "http://some.url.1", success, failure );

Can't get utf-8 upload file name in servlet on server wildfly 9.0.2

I want to upload image using servlet with server wildfy 9.0.2. But i can't get unicode utf-8 upload file name. I use code like below:
-upload.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
<center>
<h1>File Upload</h1>
<form method="post" action="UploadServlet"
enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
-UploadServlet.java
#WebServlet("/UploadServlet")
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class UploadServlet extends HttpServlet {
/**
* Name of the directory where uploaded files will be saved, relative to
* the web application directory.
*/
private static final String SAVE_DIR = "uploadFiles";
/**
* handles file upload
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + SAVE_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
System.out.println(fileName);
part.write(savePath + File.separator + fileName);
}
request.setAttribute("message", "Upload has been done successfully!");
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
/**
* Extracts file name from HTTP header content-disposition
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
When i run project and upload image i get file name like below:
éåãå³ä»æ§å¤æ´ã®ãç¥ãã.png
Please help me !
Issue seems to be in your servlet. You might have to look this code.
//read uploaded file as a parameter
RequestParameter uploadedFile = request.getRequestParameter("file");
//read uploaded file in stream
InputStream fileStream = uploadedFile.getInputStream();
This "fileStream" has file content. you could get it from this.
I hope, this will help you.
--
Jitendra

Sending form in json to servlet and doing validation

So i have this form with user name and password. I need to convert the form data in json and send it to a servlet, unpack the data do the validation and return the result back in json format to the browser. At the browser end i need to unpack and show the result.
Okay, so far i have written code to generate a json object from the form and send it to the servlet. Now i need help in receiving it at the servlet end to do validation.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="js/jquery-1.11.2.js"></script>
<script>
function sendrequest()
{
var fname= document.getElementById("Fname").value;
var password= document.getElementById("pass").value;
alert("inside function" + fname+" "+password);
var jsonstring="{\"fname\":\""+fname+"\",\""+"password\":\""+password+"\"}";
//var jsonstring='{"fname":'+fname+"\",\""+"password:"+password+"}';
alert(" jsonstring " + jsonstring);
document.getElementById("mesg").innerHTML=jsonstring;
var obj = JSON.parse(jsonstring);
$.ajax({
url: 'Chk',
type: 'GET',
data: {jsons: obj},
error: function() {
document.getElementById("mesg").innerHTML="there is error";
},
dataType: 'text',//'json'
success: function(data) {
document.getElementById("mesg").innerHTML="working";
alert("working");
document.getElementById("mesg").innerHTML=data;
}
});
}
</script>
</head>
<body>
User name:<input type="text" id="Fname" name="Fname" maxlength="12" size="12"/> <br/>
Password:<input type="text" id="pass" name="pass" maxlength="12" size="12"/> <br/>
<input type="button" value="fwd" onClick="sendrequest();"/>
<div id="mesg">252</div>
</body>
</html>
Servelet code :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String json = request.getParameter("jsons").toString();
// 1. get received JSON data from request
}
I have looked at many example not sure how to parse this. Any help will be deeply appreciated.
I think, you can use json parse library.
JSON Simple is usually using library for parsing json string.
http://code.google.com/p/json-simple/
If you want to find any other library,
visiting "http://www.json.org/" and find text java.
You can find other libraries.

Categories