i have done file uploading partially successful .the file with extension-.html,.jpeg,.pdf etc works fine.when it comes to .zip,.rpm,.tar.gz it doesn't works.the file is getting transferred to the desired path but the file is corrupted.
<tr>
<td>FileName</td>
<td><input type="text" name="filename" size="30"/></td>
</tr>
<tr>
<td>Select main category</td>
<td>
<select name="main">
<option >--Select--</option>
<option>aerospace</option>
<option>automotive</option>
<option>energy</option>
<option>icengines</option>
<option>wind</option>
<option>turbo</option>
<option>it</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Select sub category</td>
<td>
<select name="sub">
<option >--Select--</option>
<option>internal</option>
<option>demo</option>
<option>best practice</option>
<option>marketing</option>
<option>papers & public</option>
<option>validation</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Upload File</td>
<td><input type="file" name="file1"/></td>
</tr>
it will get the filename along with the dropdown values and type="file",the file is transferred to the desired path but the file is corrupted for above mentioned formats(i have checked with those formats alone).i need all the file to be stored without getting corrupted.
my servlet:
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;
private String filename="";
private String main1="";
private String location;
private String sub;
private File uploadFile;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = fileUpload.parseRequest(request);
Iterator ir = items.iterator();
while(ir.hasNext()){
FileItem item = (FileItem)ir.next();
if(item.isFormField())
{
String name = item.getFieldName();
if(name != null)
{
if(name.equals("userName"))
{
filename = item.getString();
}
else if(name.equals("main"))
{
main1 = item.getString();
}
else if(name.equals("sub"))
{
sub=item.getString();
}
}
}else{
location = File.separator+"home"+File.separator+"adapco"+File.separator+"Desktop"+ File.separator +"output"+ File.separator +main1+File.separator+sub+File.separator+filename;
uploadFile = new File(location);
long size = item.getSize();
if(size <= 1024*1024*1024)
{
item.write(uploadFile);
out.println("Your File is uploaded successfully ");
}else{
out.println("Your File is not uploaded.File size should be less than 1gb");
}
}
}
} catch (Exception e) {
}
}
}
Related
I have written a simple JSP Code to upload a PDF file into Mysql BLOB Database
My HTML code is
<form method="post" action="uploadfile.jsp" enctype="multipart/form-data">
<center>
<table border="1" width="25%" cellpadding="5">
<thead>
<th colspan="3">Upload File</th>
</thead>
<tbody>
<tr>
<td>Title : </td>
<td><input type="text" name="title" size="30"></td>
</tr>
<tr>
<td>Choose File : </td>
<td><input type="file" name="file_uploaded" /></td>
</tr>
<tr>
<td colspan="3"><center><input type="submit" value="Upload"></center></td>
</tr>
</tbody>
</table>
</center>
</form>
My JSP Code is
<%#page import="java.io.*" %>
<%#page import="java.sql.*" %>
<%
response.setContentType("text/html;charset=UTF-8");
InputStream inputStream = null;
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
String title=(request.getParameter("title"));
Part filePart = request.getPart("file_uploaded");
if (filePart != null)
{
out.println(filePart.getName());
out.println(filePart.getSize());
out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
String idTemp="1";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/fileupload","root","password");
String sql = "INSERT INTO files (id, title, file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
if (inputStream != null)
{
st.setBinaryStream(3, inputStream, (int) filePart.getSize());
}
int row = st.executeUpdate();
if (row > 0)
{
out.println("File uploaded!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
}catch(Exception e){out.print(e);}
%>
After executing this code. I am getting the error "java.sql.SQLException: No value specified for parameter 3"
What is the Problem with this code. My database table is empty , i cant able to upload any pdf data
My Database SQL is
create table files(id int(4),title varchar(20),file mediumblob,primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
You are getting error in this section.
String sql = "INSERT INTO files (id, title, file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
Here you need to add another parameter. You added only two parameter but in your query you declare three parameter by values (?, ?, ?)
I just created a Servlet code.Now its working well
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
#WebServlet("/uploadServlet")
#MultipartConfig(maxFileSize = 16177215)
public class UploadFileController extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
String idTemp=request.getParameter("id");
String title=(request.getParameter("title"));
String site=request.getParameter("site");
Part filePart = request.getPart("file_uploaded");
HttpSession hs=request.getSession(true);
hs.setAttribute("site", site);
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","password");
String sql = "INSERT INTO files (id, title,file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
//st.setString(3, site);
if (inputStream != null)
{
st.setBinaryStream(3, inputStream, (int) filePart.getSize());
}
int row = st.executeUpdate();
if (row > 0)
{
String fileuploaded="fileuploaded";
out.println("<script> alert("+fileuploaded+")</script>");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
}catch(Exception e){out.println(e);}
}
}
I have a dependency dropdown list in my JSP. I have a json servlet where I populate the second dropdown. Based on the selection made for the first dropdown will determine the second dropdown. I have hardcoded values within the jsonServlet class but I want to be able to call a query from my DAO method. How would I go about this?
JsonServlet:
package master.service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
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 master.dao.MasterDataDao;
import master.dto.SiteDto;
import com.google.gson.Gson;
/**
* Servlet implementation class JsonServlet
* #param <E>
*/
public class JsonServlet<E> extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
MasterDataDao masterDataDao = new MasterDataDao();
String divisionIdName = request.getParameter("divisionIdName");
List<String> list = new ArrayList<String>();
List<SiteDto> site = new ArrayList<SiteDto>();
String json = null;
if (divisionIdName.equals("33") || divisionIdName.equals("36")) {
try {
site.equals(masterDataDao.getAllJJSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
}
} else if (divisionIdName.equals("Select Division")) {
list.add("Select Site");
} else {
try {
site.equals(masterDataDao.getAllSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json = new Gson().toJson(list);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
Based off the divisionID selection in my JsonServlet, if the divisionID is either 33 or 36 i'd like to call this method in my MasterDataDao class:
public List<SiteDto> getAllJJSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 3050 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Otherwise if it is another selection value(besides Select Division), I'd like to call this method with the MasterDataDao class:
public List<SiteDto> getAllSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 105 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Is this possible to do within the JsonServlet? If so how? Thanks in advance.
Please let me know if more information is needed.
Also I have included my JSP here. Initially I had made a call to the DAO from here. I referenced a bean.
JSP:
<script>
$(document).ready(function() {
$('#divisionId').change(function(event) {
var divisionId = $("select#divisionId").val();
$.get('JsonServlet', {
divisionIdName : divisionId
}, function(response) {
var select = $('#siteId');
select.find('option').remove();
$.each(response, function(index, value) {
$('<option>').val(value).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<form name="input" action="getMasterData" method="get">
<br /> <br />
<h1 align='center'>Master Data File</h1>
<br /> <br />
<table border="0" align='center'>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'><jsp:useBean id="masterDaoUtil"
class="master.dao.util.MasterDataConstants" />
<select name="divisionId" id="divisionId">
<option>Select Division</option>
<option value="33">
<%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31">
<%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34">
<%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35">
<%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23">
<%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="36">
\
<%=MasterDataConstants.DIVISION_TYPE_QUALITY_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="40">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="43">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="41">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="42">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="44">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
</option>
</c:forEach>
--%>
</select></td>
</tr>
</table>
<br /> <br />
<div style="text-align: center">
<input type="submit" value="Submit">
</div>
</form>
<%
if (request.getAttribute("message") != null) {
%>
<p>
<font size=4 color="red"> Master_Data(timestamp).xlsx and
Consistency_Check_Data(timestamp).xlsx are located under
d:/stage/MasterDataReports <%--Master_Data(timestamp).xlsx and Consistency_Check_Data(timestamp).xlsx are located under /jsc/ets/u02/tools7/apache-tomcat-7.0.55/webapps/MasterData/MasterDataReport--%>
</font>
</p>
<%
}
%>
Originally before I used JSON and AJAX I used this statement for the options which is now commented out.
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
Is there a way I can leverage this? Maybe can I make a function call to the JSP from my servlet? I know this is not good practice but I cannot think of another way. I need to get the siteDto.id value as well as the siteDto.name value.
Thanks in advance
Create an interface and implementation DAO like IMasterDataDAO and MasterDataDAOImpl.
In case if you get more if..else condition in future then use switch..case instead of if..else.
Create an object for DAO using the interface in servlet like below:
IMasterDataDAO masterDAO = new MasterDataDAOImpl()
then call either masterDAO.getAllJSites() or masterDAO.getAllSites() based on the condition.
This question already has answers here:
Force a checkbox to always submit, even when unchecked
(7 answers)
Closed 6 years ago.
I need help in inserting the unchecked value of a check box into mysql database using servlet.
Work Flow:
1.From a list of check box values the user checks some of the values and the remaining values are set unchecked
2.After selecting the values the user hits the save button
3.On clicking the save button,the checked values should be stored in one table and the unchecked values should be stored in another table
Issue
I have used the general method to insert the values into database,for me the checked values are getting inserted into one table(pdt_list).In the same way I need to insert the unchecked values into another table say(no_pdt_list). Both the insertion should happen once the save button is clicked.
This is my code
products.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
Servlet code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs=null;
Connection connection = null;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
prep.close();
}
catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
}
finally {
try {
connection.close();
}
catch (Exception ex) {
System.out.println("The error is"+ex.getMessage());
}
}
}
}
Do you use Jquery as well?, you could try doing:
$("input:checkbox:not(:checked)") and saving it in a hidden field before submitting the form when you hit "Save"...
Be sure to reference the name of your checkbox if you have more than one set os checkboxes in your page.
i.e:
$("input#prod:not(:checked)").each(function(i){
console.log($(this).val()); //or save it to the hidden value with a comma or some sort of separator you can then work with at the servlet
});
I'm trying to insert an image in a MySQL database using Servlet and JSP in Tomcat 7. When I click on the save button, it displays null. I am not getting any errors.
Also I set commons-fileupload.jar file and commons-io.jar file. If you have some demonstration code, please give me.
<%# 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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table
</form>
</center>
</body>
</html>
FileUploadDBServlet.java:
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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;
#WebServlet("/FileUploadDBServlet")
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/AppDB";
private String dbUser = "root";
private String dbPass = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
String sql =("INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)");
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (Exception ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/FileUploadDBServlet</url-pattern>
</servlet-mapping>
</web-app>
The following code explains how to store/retrieve an image to/from db.
First create a table in your db using following code
CREATE TABLE contacts (
contact_id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
photo` mediumblob);
Create a jsp file for input parameters.
Upload.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database</title>
</head>
<body>
<h1>File Upload to Database</h1>
<form name="fileform" method="post" action="uploadServlet" enctype="multipart/form-data">
<label for="firstName">First Name:</label>
<input type="text" name="firstName" size="50" placeholder="Enter Your FirstName" required/><br><br>
<label for="lastName">Last Name: </label>
<input type="text" name="lastName" size="50" placeholder="Enter Your LastName" required/><br><br>
<label for="photo"> Portrait Photo: </label>
<input type="file" name="photo" size="50" placeholder="Upload Your Image" required/><br><br>
<input type="submit" value="Save">
</form>
</body>
</html>
Next create controller for uploading image. In this case, I'm using a servlet.
FileUploadDbServlet.java:
package com.fileupload.attach;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#MultipartConfig(maxFileSize = 16177215)
// upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
private static final int BUFFER_SIZE = 4096;
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/mysql";
private String dbUser = "root";
private String dbPass = "arun";
//naive way to obtain a connection to database
//this MUST be improved, shown for
private Connection getConnection() {
Connection conn = null;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
} catch (Exception e) {
//wrapping any exception and rethrowing it
//inside a RuntimeException
//so the method is silent to exceptions
throw new RuntimeException("Failed to obtain database connection.", e);
}
return conn;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
//obtains input stream of the upload file
//the InputStream will point to a stream that contains
//the contents of the file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
conn = getConnection();
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
//Using a PreparedStatement to save the file
PreparedStatement pstmtSave = conn.prepareStatement(sql);
pstmtSave.setString(1, firstName);
pstmtSave.setString(2, lastName);
if (inputStream != null) {
//files are treated as BLOB objects in database
//here we're letting the JDBC driver
//create a blob object based on the
//input stream that contains the data of the file
pstmtSave.setBlob(3, inputStream);
}
//sends the statement to the database server
int row = pstmtSave.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
String filepath = "D:/Dev/JavaWorkSpaceNew/FileUploadDatabase/WebContent/FromDb.jpg";
//Obtaining the file from database
//Using a second statement
String sql1 = "SELECT photo FROM contacts WHERE first_name=? AND last_name=?";
PreparedStatement pstmtSelect = conn.prepareStatement(sql1);
pstmtSelect.setString(1, firstName);
pstmtSelect.setString(2, lastName);
ResultSet result = pstmtSelect.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("photo");
InputStream inputStream1 = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filepath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream1.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream1.close();
outputStream.close();
System.out.println("File saved");
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
//silent
}
}
// sets the message in request scope
request.setAttribute("message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp")
.include(request, response);
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>servletFileUpload</display-name>
<welcome-file-list>
<welcome-file>Upload.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>FileUploadDBServlet</display-name>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>com.fileupload.attach.FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
Message.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<h3>Result of the operation: ${message}</h3>
</body>
</html>
Jsp Page
Save this page with any name
<%#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 action="abc" method="post" enctype="multipart/form-data"> <br><br>
<table>
<tr>
<td>UserName: </td>
<td width='10px'></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Upload: </td>
<td width='10px'></td>
<td><input type="file" name="file" value="Upload"/></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Servlet page and save this page as abc.java
source code
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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;
#WebServlet(urlPatterns = {"/abc"})
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 100)
public class abc extends HttpServlet {
// this if directory name where the file will be uploaded and saved
private static final String SAVE_DIR = "images";
// this is the method which is created by system it self
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// this tyr is created by me for the connection of database
try {
// this is the path provide by me to save the image
String savePath = "C:" + File.separator + SAVE_DIR;
/*in place of C: you can place a path wher you need to save the image*/
// this comment will picup the image file and have convert it into file type
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// this two comment will take the name and image form web page
String name = request.getParameter("name");
Part part = request.getPart("file");
// this comment will extract the file name of image
String fileName = extractFileName(part);
// this will print the image name and user provide name
out.println(fileName);
out.println("\n" + name);
/*if you may have more than one files with same name then you can calculate
some random characters and append that characters in fileName so that it will
make your each image name identical.*/
part.write(savePath + File.separator + fileName);
/*
You need this loop if you submitted more than one file
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}*/
// connectio to database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("url", "host -name", "password");
// query to insert name and image name
String query = "INSERT INTO image_link (name,photourl) values (?, ?)";
PreparedStatement pst;
pst = con.prepareStatement(query);
pst.setString(1, name);
String filePath = savePath + File.separator + fileName;
pst.setString(2, filePath);
pst.executeUpdate();
} catch (Exception ex) {
out.println("error" + ex);
}
}
}
// the extractFileName() is method used to extract the file name
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 "";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
I want to upload a file in apache tomcat and save data in the MySQL from text field using JSP. On doing so, I could not pass the value from JSP page to Servlet and save in Database.
How can I do it?
I tried the following lines of code:
JSP:
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input name="a" type="text"/>
<br />
<input type="submit" value="Upload File" />
</form>
And also I used the following lines of code in Servlet:
Servlet
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 10000 * 1024;
private int maxMemSize = 5 * 1024;
private File file;
String gi;
#Override
public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
protected void processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
gi =request.getParameter("a");
if (!isMultipart) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\Software\\apache-tomcat-7.0.29\\webapps\\Hello\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
} catch (Exception ex) {
out.println("Your file size should be less than 10 or equal to 10kb" + ex);
}
try {
/* TODO output your page here. You may use following sample code. */
out.println("<h1>"+gi+"</h1>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webSiteTest", "root", "root");
PreparedStatement stat = conn.prepareStatement("insert into abc(name) values (?)");
stat.setString(1, gi);
int aa = stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Database Connected Successfully.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Query Error!");
} catch (ClassNotFoundException ee) {
JOptionPane.showMessageDialog(null, "Database not Found!");
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
processRequest(request, response);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
//throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
processRequest(request, response);
}
}
How can I do this.
Create file object that points to a file specified by you in JSP.
and in JSP do,
request.setAttribute("file",fileObject);
and in Servlet get that object using
request.getAttribute("file");
try this.it should work.
To send a file through a JSP/servlet we need a commonsio.jar file and this will be easily found in the google. Now place that jar file in the lib directory of the tomcat folder and Now it will work.