How can i add progress bar to this java upload file example? - java

I'm creating a JSP/Servlet web application and I'd like to upload a file to a Servlet with progress bar.
This is an example of uploading file with jsp and servlet.
Its working but i want to add to it a progress bar.
The FileUploadHandler.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet to handle File upload request from Client
* #author Javin Paul
*/
public class FileUploadHandler extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "uploads";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
String name = null;
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
name = new File(item.getName()).getName();
item.write( new File(uploadPath+name));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully "+uploadPath+ name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
The upload.jsp
<%#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>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
The result.jsp
<%#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>File Upload Example in JSP and Servlet - Java web application</title>
</head>
<body>
<div id="result">
<h3>${requestScope["message"]}</h3>
</div>
</body>
</html>
The web.xml
<servlet>
<servlet-name>FileUploadHandler</servlet-name>
<servlet-class>FileUploadHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadHandler</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>

Though late, try using following plugin, which makes your UI beautiful and super easy.
https://github.com/blueimp/jQuery-File-Upload
Java examples are as follows:
https://github.com/blueimp/jQuery-File-Upload/wiki

Related

Java-IO UTF-8 encoding problem to save html file

What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?

jsp form text + file processing

bookReg.jsp
<%#page import="classes.BooksDTO"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="css/mainStyle.css">
</head>
<body>
<%
//D:\Hayden\учеба\джава\JavaBigData\readers\WebContent\img - folder directory
%>
<form action="bookRegProc.jsp" method="post" enctype="multipart/form-data">
Title <input type="text" name="title"> <br>
Plot <textarea rows="30" cols="40" name="plot"></textarea> <br>
<input type="hidden" name="rating" value="0"> <br>
Author <input type="text" name="author"> <br>
Publisher <input type="text" name="publisher"> <br>
Genre <input type="text" name="genre"> <br>
Publication date <input type="text" name="date"> <br>
Cover <input type="file" name="cover" size="50"> <br>
<input type="submit" value="Register"> <br>
</form>
</body>
</html>
bookRegProc.jsp
<%#page import="classes.Uploader"%>
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="java.io.File"%>
<%#page import="classes.BooksDTO"%>
<%#page import="classes.BooksDAO"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Uploader upload = new Uploader();
upload.doPost(request, response);
%>
</body>
</html>
Uploader.java
package classes;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Uploader extends HttpServlet {
BooksDTO dto = null;
BooksDAO dao = new BooksDAO();
String title = null;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title"); // Retrieves <input type="text" name="description">
String plot = request.getParameter("plot");
String rating = request.getParameter("rating");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
String genre = request.getParameter("genre");
String date = request.getParameter("date");
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
/*String fileName = title;
InputStream fileContent = filePart.getInputStream();*/
// ... (do your job here)
//DTO process
BooksDTO dto = new BooksDTO();
BooksDAO dao = new BooksDAO();
dto.setTitle(title);
dto.setAuthor(author);
dto.setDate(date);
dto.setGenre(genre);
dto.setPlot(plot);
dto.setPublisher(publisher);
dto.setRating(rating);
try {
dao.insert(dto);
//this inserts all the parameters into database
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//File process
File file;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
String filePath = "D:/Hayden/Eclipse workspace/bigdata/readers/WebContent/img/";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("C:/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
FileItem fi = (FileItem) filePart;
if(!fi.isFormField()) {
file = new File(filePath + dto.getTitle() + ".jpg");
fi.write(file);
}
}catch(Exception ex) {
System.out.println(ex);
}
}
}
I want to pass text parameters from bookReg.jsp to register it in my database.
I checked the methods for inserting into database works totally fine.
but in doPost method, Uploader.java, request.getParameter passes null to each String.
I searched how to pass text to a servlet for days and I finally followed this instruction : How to upload files to server using JSP/Servlet? (first answer)
but it still passes null only.
what is the difference between passing parameter using request.getParameter in jsp and in a java class as I wrote?
and what is causing the same problem even if I followed the instruction of the first answer in the page that I followed?
(I am using tomcat 8.5 and eclipse oxygen)

Display image on JSP page using mySql [duplicate]

This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 5 years ago.
Please help me in displaying image in a particular section on a JSP page which is stored in mySql database and also tell me that can we store image in any datatype?
Web pages display images from URLs.
You can either encode the image in a data: URI, or write server-side code to serve it in response to some URL.
add this servlet to your project like this :
package com.app.meservlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.app.upload.UploadPicture;
/**
*
* #author user-sqli date: 12/05/2016 17:42
*/
#WebServlet(urlPatterns = "/upload", loadOnStartup = 1)
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class ControllerUploadPicture extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String appPath = request.getServletContext().getRealPath("");
Part part = request.getPart("file");
UploadPicture.createNewInstance().TranseferPicture(part, appPath);
getServletContext().getRequestDispatcher("/show.jsp").forward(request,
response);
}
}
and add this classto your project :
package com.app.upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Part;
/**
*
* #author user-sqli date: 12/05/2016 17:30
*/
public class UploadPicture {
private static final String EXTENSION = ".";
public static final String SAVE_DIR = "uploadImage";
private static UploadPicture uploadPicture = null;
private static final Logger LOGGER = Logger.getLogger(UploadPicture.class
.getName());
private UploadPicture() {
}
public String TranseferPicture(Part part, String appPath) {
String savePath = appPath + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String nameImage = fileName + EXTENSION + getExtensionImage(part);
try {
part.write(savePath + File.separator + nameImage);
LOGGER.log(Level.FINE, "Upload Picture to {0} ", savePath
+ File.separator + nameImage);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.toString(), ex);
}
return nameImage;
}
private String getExtensionImage(Part part) {
return part.getContentType().split("/")[1];
}
public static UploadPicture createNewInstance() {
if (uploadPicture == null) {
uploadPicture = new UploadPicture();
}
return uploadPicture;
}
}
in your jsp like this :
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="submit"
value="Upload" />
</form>
</body>
</html>
and for shoing this image :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
uploaded image sucess.
<%-- <img width="100px" height="100px" src="<c:url value="/uploadImage/${name}" />"> --%>
</body>
</html>
this example require servlet >=3.1

How do we print a counter from a servlet to a jsp?

Hey I am trying to create a voting app.
I have several counters in my servlets and I want to be able to display the value of those counters in my jsp file. How do I do it?
Please help me.
I want to display the total number of votes in each section and the winner after the election.
......................................................................................................................................................
servlet file
......................................................................................................................................................
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/CastVote")
public class CastVote extends HttpServlet {
int javaCount, phpCount, pythonCount, othersCount;
public CastVote() {
super();
javaCount = 0;
phpCount = 0;
pythonCount = 0;
othersCount = 0;
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("language");
if("java".equals(choice))
{
javaCount++;
}
else if("php".equals(choice))
{
phpCount++;
}
else if("python".equals(choice))
{
pythonCount++;
}
else if("others".equals(choice))
{
othersCount++;
}
}
}
......................................................................................................................................................
Jsp File
......................................................................................................................................................
<%# 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>Vote now.</title>
</head>
<body>
<center>
<h2>Welcome to voting portal. Cast your vote.</h2>
</center>
<form action="CastVote" method="post">
Which of the following is the best language for backend programming? <br>
<input type="radio" name="language" value="java">1) Java <br>
<input type="radio" name="language" value="php">2) PHP <br>
<input type="radio" name="language" value="python">3) Python <br>
<input type="radio" name="language" value="others">4) Others <br>
<input type = "submit" value ="Vote">
</form>
</body>
</html>

Linking a jsp page to a java class

I have written a hello world program in jsp and now i am trying to process forms via JSP.
My jsp form(GetName.jsp) looks like this
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<FORM METHOD=POST ACTION="SaveName.jsp">
Name <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
Email <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
Age <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
</body>
</html>
Similarly SaveName.jsp looks like this
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="userData" class="javabeans.UserData" scope="session"/>
<jsp:setProperty name="userData" property="*"/>
</BODY>
</HTML>
</body>
</html>
And in the same project in a package named javabeans the class named UserData looks like this.
package javabeans;
public class UserData {
String username;
String email;
int age;
public void setUsername( String value )
{
username = value;
}
public void setEmail( String value )
{
email = value;
}
public void setAge( int value )
{
age = value;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }
}
Now when run GetName.jsp i get the following errors
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:56: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
UserData user = null;
^
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:58: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = (UserData) _jspx_page_context.getAttribute("user", PageContext.SESSION_SCOPE);
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:60: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = new UserData();
3 errors
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:930: The following error occurred while executing this line:
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:284: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 2 seconds)
You need to import UserData class inside SaveName.jsp
Add this to the top of your jsp code in SaveName.jsp
<%# page import="javabeans.UserData" %>
I'm not sure what you want to implement over here but i can give you simple idea about jsp servlets
first you can create a simple jsp program. it will ask the user for name and email id and on form action redirect it to abc servlet.
<%# 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> My first JSP </title>
</head>
<body>
<form action="abc">
Please enter a name <br>
<input type="text" name="name"size="20px">
Please enter an email <br>
<input type="text" name="email"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
and then create the "abc" servlet
place this code in your servlet. it will get the value from jsp page and display it.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class abc extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// reading the user input
String name= request.getParameter("name");
String email= request.getParameter("email");
String msg="I'm"+name+"id is"+email;
PrintWriter out = response.getWriter();
out.println (
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html> \n" +
"<head> \n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html;
charset=ISO-8859-1\"> \n" +
"<title> Hi </title> \n" +
"</head> \n" +
"<body> \n" +
msg +
"</font> \n" +
"</body> \n" +
"</html>"
);
}
}
Define your servlet in "web.xml" . you need to do servlet mapping in web.xml file.
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>abc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>

Categories

Resources