jsp servlet file upload doGet - java

I can upload a file in a servlet using the apache commons FileUpload. The code below worked in the processRequest method off the servlet, but I copy Pasted the code in the doPost method and now it doesn't work anymore. the line
List fileItems = upload.parseRequest(request);
makes an empty array of fileItems.
How can this be?
Here is the full doPost method
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int fileId = 0;
String LogicalName = "";
String PartNr = "";
String Cost = "";
String Assembly = "";
String Comment = "";
try {
Connection conn = MysqlConnect.conn();
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
switch (fieldname) {
case "logicalName":
LogicalName = fieldvalue;
break;
case "partNr":
PartNr = fieldvalue;
break;
case "cost":
Cost = fieldvalue;
break;
case "assembly":
Assembly = fieldvalue;
break;
case "comments":
Comment = fieldvalue;
break;
}
} else {
PrintWriter out = response.getWriter();
File file;
int maxFileSize = 500000 * 1024;//max 500 mb groot
int maxMemSize = 5000 * 1024;//max 5mb gecached in het ram,indien file groter is eerst wegschrijven in een temp dir
String filePath = "C:\\uploads\\";
String fileName = "";
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("c:\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
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);
}
}
HttpSession session = request.getSession();
int uploader = (Integer) session.getAttribute("UserId");
String Query = "Insert into tbl_file (fileLocation,Uploader)values(\"" + fileName + "\"," + uploader + ");";
PreparedStatement st = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
if (rs.next()) {
fileId = rs.getInt(1);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
if (fileId == 0) {
//ERROR
} else {
Statement stmt = conn.createStatement();
String Query1 = "Insert into tbl_part (partCad,partCost,partAssembly,partMotivation,partOf) VALUES(" + fileId + "," + Cost + "," + Assembly + ",\"" + Comment + "\"," + "1" + ");";
stmt.executeUpdate(Query1);
}
MysqlConnect.close(conn);
} catch (SQLException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
String URL = "/home.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL);
dispatcher.forward(request, response);
}
And This is the JSP
<%# 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/Racing/UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" />
<br />
Logische Naam: <input type="text" name="logicalName"><br>
Stuknr(automatisch,nog niet geimplementeerd): <input type="text" name="partNr"><br>
Kost: <input type="text" name="cost"><br>
Assembly:
<select name = "assembly">
<c:forEach var ="assembly" items="${Assemblys}">
<option value="${assembly.id}">${assembly.name}</option>
</c:forEach>
</select>
<br>
<textarea name="comments" cols="25" rows="5">
Verdediging Design
</textarea><br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
Many thanks in advance!

Your code line List fileItems = upload.parseRequest(request); and even all the lines in the else part doesn't have any sense at all because:
You already have processed the request before in this line
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
No need to process the request again.
You already have the file you want/need to process in the item object which isFormField method returns false.
Change your method in order to look like here: How to upload files to server using JSP/Servlet?:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
switch (fieldname) {
case "logicalName":
LogicalName = fieldvalue;
break;
//other case statements...
}
} else {
//here you only have to process the file
File file;
int maxFileSize = 500000 * 1024;//your comments...
int maxMemSize = 5000 * 1024;//your comments...
//this must be a constant or a servlet init param, do not hard code it
String filePath = "C:\\uploads\\";
String fileName = FilenameUtils.getName(item.getName());
factory.setSizeThreshold(maxMemSize);
//didn't you have a filePath variable?
factory.setRepository(new File("c:\\temp"));
upload.setSizeMax(maxFileSize);
try {
String fieldName = fi.getFieldName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
file = new File(filePath, fileName);
item.write(file);
//code to save your file location in db...
//note: this MUST BE in a business logic method, not directly written in your servlet
HttpSession session = request.getSession();
int uploader = (Integer) session.getAttribute("UserId");
} catch (Exception ex) {
//very BAD idea
//use a logger instead like log4j or sfl4j
System.out.println(ex);
}
}
}
Additional: check the File(String parent, String child) constructor.

Related

Image save, edit, delete to specific folder and save path and other data in database in java (jsp, servlet,mysql)

I want to get image from jsp page save it specific folder which is out of the server container and path of image and other details (i.e. name, path,etc) store in mysql database, after that user need to able to update the image (delete, add more images,etc).
Now I am able to store the image in specific folder and path and other details in database, now am stuck in how to get the actual image from folder to the jsp page as per the path getting from sql database.
There is any example which help me regarding that.
CODE:
private static final long serialVersionUID = 1L;
public BasicInfoFrmDao dao;
int page = 1;
int recordsPerPage = 5;
public static final String MUNCIPAL_COUNCIL_FORM = "/mc-basic-form-list.jsp";
public BasicFormImageController() {
dao = new BasicInfoFrmDaoImplementation();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
String sessionUserName = (String) session.getAttribute("username");
int sessionUserId = (Integer) session.getAttribute("user_id");
System.out.println("session Username = : " + sessionUserName + " & UserId = : " + sessionUserId);
List<BasicInfoFrm> basicInfoFrms = dao.getAllMuncipalCouncils((page - 1) * recordsPerPage, recordsPerPage,
sessionUserId);
for (BasicInfoFrm bc : basicInfoFrms) {
int i = bc.getMuncipalCouncilId();
System.out.println("muncipal id : " + i);
}
request.setAttribute("mcouncils", basicInfoFrms);
int noOfRecords = dao.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
request.setAttribute("alertMsg", "Your information saved successfully...... Thank You!");
RequestDispatcher requestDispatcher = request.getRequestDispatcher(MUNCIPAL_COUNCIL_FORM);
requestDispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OrgImage orgImage = new OrgImage();
int orgId = 0;
int step = 0;
ArrayList<String> path = new ArrayList<String>();
// String orgId = request.getParameter("basicInfoFrmId2");
// System.out.println("org id = "+orgId);
// ======================================
// Uploading multiple images at specific folder and path in DB
// 07-12-2017....
ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
try {
List<FileItem> multiFiles = sf.parseRequest(request);
for (FileItem item : multiFiles) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
System.out.println("text fieldName" + fieldName);
String fieldValue = item.getString();
System.err.println("text fieldValue " + fieldValue);
// ... (do your job here)
if (fieldName.equalsIgnoreCase("basicInfoFrmId")) {
orgId = Integer.parseInt(fieldValue);
step = 4;
orgImage.setOrgId(orgId);
}
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
System.out.println("fieldName " + fieldName);
String fileName = FilenameUtils.getName(item.getName());
System.out.println("fileName " + fileName);
InputStream fileContent = item.getInputStream();
System.out.println("fileContent " + fileContent);
// ... (do your job here)
try {
item.write(new File("/myDemoFileFolder/" + item.getName()));
path.add("c:/myDemoFileFolder/" + item.getName());
// file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
// file.mkdirs();
System.out.println("Your file " + item.getName() + " is uploaded successfully...");
}
orgImage.setImagePath(path);
System.out.println("org id = " + orgId);
System.out.println("step = " + step);
// send data to server 08-12-2017....
if (orgId != 0) {
int lastlyEnteredImgId = dao.addOrgImages(orgImage);
System.out.println("Lastly entered Basic Information Img Id : " + lastlyEnteredImgId);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// Up to yet.....Uploading multiple images at specific folder
// and path in DB 07-12-2017....
// ====================================
doGet(request, response);
}
I got the proper solution "http://balusc.omnifaces.org/2007/04/imageservlet.html" here.
Create the separate servlet and pass image path in and got the image in the jsp page.

How to pass input value from multipart/form-data in jsp to servlet?

I know that maybe it can be a duplicated question, i read similar post on internet, but i cannot send my input value from jsp to servlet.
I can upload file but i need to send an input value.
Servlet:
try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
out.println("--------------");
out.println("fileName = " + fileName);
out.println("Kind = " + fileNameWithOutExt);
out.println("field name = " + fieldName);
out.println("contentType = " + contentType);
String fileContents = null;
try {
fileContents = IOUtils.toString(in);
out.println("lenght: " + fileContents.length());
String[] content = fileContents.split("\n");
String[] property = content[0].split(",");
out.println("lunghezza " + property.length);
for (String propr : property) {
out.println("prop: " + propr);
}
//out.println(Arrays.toString(property));
//out.println(fileContents);
} finally {
IOUtils.closeQuietly(in);
}
}
}
} catch (SizeLimitExceededException e) {
out.println("You exceeded the maximu size ("
+ e.getPermittedSize() + ") of the file ("
+ e.getActualSize() + ")");
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
And that's my jsp
<form action="/upload_kind" method="post" enctype="multipart/form-data" >
<input type="file" name="file" size="50" />
<input type="text" name="namespace" id="namespace">
<br />
<input type="submit" value="Upload File" />
</form>
I read about a "item.getString()" method but it's in DiskFileItem class and not in FileItemStream, so i can see that "namespace" is sent, but i cannot see its value.
Thx and sorry for my bad english
Following the duplicated link, i was able to resolve my problem. I used this code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}

How to store data of excel by browsing the file in mysql database table using jsp [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
I'm new to Apache Poi and File handling java.So i want some help
I had done by excel file path in the code but now i want to do without giving filepath in code.
So now my question is
How to store data of excel by browsing the file in mysql database table using jsp???
I want to select the excel file by browsing the computer.
index.jsp
<body>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<table>
<tr>
<td ><B>UPLOAD THE FILE</B></td>
</tr>
<tr>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr>
<td><input type="submit" value="Upload File"> </td>
</tr>
</table>
</form>
</body>
upload.jsp
<body>
<%# page import="java.io.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*"%>
<%# page import="org.apache.poi.ss.usermodel.*"%>
<%# page import="org.apache.poi.xssf.usermodel.XSSFSheet"%>
<%# page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>
<%
String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
{
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength)
{
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%>
<table>
<tr>
<td><b>You have successfully upload the file:</b>
<% out.println(saveFile);
%>
</td>
</tr>
</table>
<%
Connection connection = null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
FileInputStream fileInputStream;
Statement stmt = null;
File f = null;
int count = 0;
ArrayList<String> mylist = new ArrayList<String>();
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/parag","root","tiger");
System.out.println("connection sucessfulyyy");
f = new File(saveFile);
preparedStatement = connection.prepareStatement("insert into exlogin(username) values(?)");
fileInputStream = new FileInputStream(f);
preparedStatement.setBinaryStream(1, (InputStream)fileInputStream, (int)(f.length()));
preparedStatement.executeUpdate();
System.out.println("connection sucessfulyyy");
resultSet = stmt.executeQuery("SELECT COUNT(*) FROM exlogin");
while(resultSet.next())
{
int val = resultSet.getInt(1);
System.out.println(val);
count = val+1;
}
preparedStatement.setInt(1,count);
/* We should now load excel objects and loop through the worksheet data */
fileInputStream = new FileInputStream(f);
System.out.println("FileInputStream Object created..! "+filePath);
/* Load workbook */
XSSFWorkbook workbook = new XSSFWorkbook (fileInputStream);
System.out.println("XSSFWorkbook Object created..! ");
/* Load worksheet */
XSSFSheet sheet = workbook.getSheetAt(0);
System.out.println("XSSFSheet Object created..! ");
// we loop through and insert data
Iterator<Row> ite = sheet.rowIterator();
System.out.println("Row Iterator invoked..! ");
while(ite.hasNext())
{
Row row = (Row) ite.next();
Iterator<Cell> cellIterator = row.cellIterator();
int index = 1;
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_STRING: //handle string columns
preparedStatement.setString(index, cell.getStringCellValue());
System.out.println("getting cell value..! "+cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC: //handle double data
double i = (double)cell.getNumericCellValue();
preparedStatement.setFloat(index, (float) cell.getNumericCellValue());
break;
}
index++;
}
//we can execute the statement before reading the next row
preparedStatement.executeUpdate();
}
/* Close input stream */
fileInputStream.close();
/* Close prepared statement */
preparedStatement.close();
/* Close connection */
connection.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
%>
</body>
Database Table
CREATE TABLE exlogin
(
username varchar(100)
);
Excel File Data
username
parag
ram
shree
tejas
jyoti
Thanks for any help
InputStream its access run time your file
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
InputStream inputStream= item.getInputStream();
Workbook workbook = new XSSFWorkbook(inputStream);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
Hope its help to you!!

how to read excel file using servlet jsp

I had tried to read excel file from jsp to servlet in apache tomcat.
The below code has been receive excel file from apache folder after write the file and get that file.I need to dont write in apache tomcat.How to directly read excel file values.
The following code is MyServletUpload.java .
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
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 javax.servlet.http.HttpSession;
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;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.mysql.jdbc.Statement;
import com.ppts.webwatcher.Validation.Urlvalidation;
import com.ppts.webwatcher.setting.DBConnector;
import com.ppts.webwatcher.webdownload.Webpagedownload;
#WebServlet("/MyservletUpload")
public class MyservletUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
/**
* #see HttpServlet#HttpServlet()
*/
public MyservletUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
int count = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection con = db2Connector.getConnection(true);
Statement stmt = null;
String compName = null;
String url_Name = null;
String message = null;
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("/");
// + File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println("file path : " + filePath);
item.write(uploadedFile);
FileInputStream fis = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
String h = "";
int i = 1;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (i == 1) {
h = cell.getStringCellValue();
} else {
h = h + "~" + cell.getStringCellValue();
}
i++;
}
String[] a = h.split("~");
compName = a[0].trim();
url_Name = a[1].trim();
System.out.println("company name : " + compName);
System.out.println("ulr name : " + url_Name);
try {
long ft1 = 0;
long ft2 = 0;
int lk = 0;
BufferedReader in = null;
BufferedWriter be = null;
String filenam = "";
String patr = getServletContext().getRealPath("/");
filenam = patr + "webfolder";
// System.out.println("part : " + filenam);
File filchkr = new File(filenam);
if (filchkr.exists()) {
// System.out.println("fil exists");
} else {
// System.out.println("fil not exists");
}
try {
ft1 = System.currentTimeMillis();
String line1;
// String arrsp =
// "http://www.mmrf.org/research/research.html~helwel131";
int li = compName.length();
// System.out.println("Urlname " + url_Name);
// System.out.println("companyname " +
// compName);
System.out.println("####"
+ Urlvalidation.checkInsertValidation(
url_Name, compName));
if (Urlvalidation.checkInsertValidation(
url_Name, compName) != null) {
System.out
.println("error url name >>>>>>>>> "
+ url_Name);
System.out
.println("errror url link >>>>>>>>>>>"
+ compName);
} else {
String urlreplaceText = url_Name.replace(
" ", "%20");
// System.out.println("path : "+getServletContext().getRealPath("/"));
URL url1 = new URL(urlreplaceText);
// System.out.println(url1);
String filepath = filenam + "/" + compName;
File f1 = new File(filepath);
if (!f1.exists()) {
}
boolean result = false;
try {
f1.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
String fullpath = filepath
+ "/firstdownload.html";
Webpagedownload.webdown(fullpath, url1);
lk = 1;
ft2 = System.currentTimeMillis();
long ft = ft2 - ft1;
// System.out.println(ft + ": time ");
String selection = "full_content";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(
DATE_FORMAT);
String strDateNew = sdf.format(now);
stmt = (Statement) con.createStatement();
String sql = "INSERT INTO new_table (title,url,source_selection,content,inserttime,insertvalue) VALUES ('"
+ compName
+ "','"
+ url_Name
+ "','"
+ selection
+ "','','"
+ strDateNew + "','" + '0' + "')";
stmt.executeUpdate(sql);
HttpSession session = request.getSession();
String username = String.valueOf(session
.getAttribute("username"));
String userid = String.valueOf(session
.getAttribute("userid"));
stmt.executeUpdate("insert into usersession(userid,username,createtime,urlname,urllink) values('"
+ userid
+ "','"
+ username
+ "','"
+ strDateNew
+ "','"
+ compName
+ "','" + url_Name + "')");
}
} catch (Exception e) {
System.out.println("Error: \t" + e);
System.out
.println("exception Urlname>>>>>>>>> "
+ url_Name);
System.out
.println("exception companyname >>>>>>>>>>>"
+ compName);
}
} catch (Exception e) {
System.out.println(e);
}
count++;
}
message = "success";
File file = new File(filePath);
file.delete();
}
}
getServletContext().getRequestDispatcher("/Message.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
jsp
<form method="post" action="MyservletUpload"
enctype="multipart/form-data">
Choose File : <input type="file" name="photo" size="50" /> <input
type="submit" value="Upload" onclick="uppload()">
</form>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*,java.util.*,java.io.*"%>
<%# page import="com.ppts.webwatcher.setting.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
</script>
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
<style>
.textbox {
background:
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABClpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wUmlnaHRzPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvcmlnaHRzLyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wUmlnaHRzOk1hcmtlZD0iVHJ1ZSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NzI3NTdDRTExNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NzI3NTdDRTIxNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiPiA8ZGM6cmlnaHRzPiA8cmRmOkFsdD4gPHJkZjpsaSB4bWw6bGFuZz0ieC1kZWZhdWx0Ij5DcmVhdGl2ZSBDb21tb25zIEF0dHJpYnV0aW9uIE5vbi1Db21tZXJjaWFsIE5vIERlcml2YXRpdmVzPC9yZGY6bGk+IDwvcmRmOkFsdD4gPC9kYzpyaWdodHM+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjcyNzU3Q0RGMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjcyNzU3Q0UwMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+SoKR9AAAAH5JREFUeNpi/P//PwMlgImBQsDS39/fAKTrydTfyESBZhCoR/bCAig9AYgZceAFaGpRwiARKlEAxPOx2AYSS4CqSYSHAZoimEQCGh+rZmwGYDOEAZdmXAZgMwSrZnwGMKBpSMSZDghEUyLtUyIS+z+5eaGRAgc0Mg54bgQIMAAD7RsCMDpK7QAAAABJRU5ErkJggg==)
no-repeat 10px 4px #FFF;
height: 25px;
width: 275px;
border: 1px solid #848484;
padding-left: 30px;
}
</style>
<title>UPDATE SCANNER-Updated Url</title>
</head>
<%# include file="header.jsp"%>
<body>
<SCRIPT language="JavaScript">
function OnSubmitForm()
{
if(document.pressed == 'Send Email')
{
document.myform.action ="emailaction.jsp";
}
else
if(document.pressed == 'View')
{
var slvals = [];
$('input:checkbox[name=case]:checked').each(function() {
slvals.push($(this).val());
});
var i;
for (i = 0; i < slvals.length; i++) {
var url="Multitabhelp.jsp?urlid="+slvals[i];
var win = window.open(url, '_blank');
win.focus();
}
return false;
}
return true;
}
</SCRIPT>
<center>
<b><h1>Updated URL</h1> </b>
<FORM name="myform" onSubmit="return OnSubmitForm();">
<%
int co = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection conn = db2Connector.getConnection(false);
Statement stmt = null;
Statement stmt1 = null;
String time;
String urld = request.getParameter("urlid");
System.out.println("hello " + urld);
try {
stmt = conn.createStatement();
stmt1 = conn.createStatement();
String son = "";
String b = "";
String sww = "select * from updatehistory where updatetime='"
+ urld + "' and updation='1'";
System.out.println(sww);
ResultSet rs = stmt
.executeQuery("select * from updatehistory where updatetime='"
+ urld + "' and updation='1'");
out.println("<div class='CSSTableGenerator'>");
out.println("<TABLE BORDER=1 id=\"tablepaging\" class=\"yui\" align=\"center\">");
out.println("<th>"
+ " S.No"
+ "</th>");
out.println("<th>"
+ " Date"
+ "</th>");
out.println("<th>"
+ " Source Name"
+ "</th>");
out.println("<th>"
+ " URL"
+ "</th>");
out.println("<th>"
+ " Updated Content"
+ "</th>");
%>
<th><input type="checkbox" id="selectall" /></th>
<%
out.println("<th>"
+ " <label class='col-md-3 control-label'> Action</label>"
+ "</th>");
while (rs.next()) {
time = rs.getString("date_time");
ResultSet rs11 = stmt1
.executeQuery("select * from new_table where urlid='"
+ rs.getString("urlid") + "' ");
if (rs11.next()) {
System.out.println(rs11.getInt(1));
out.println("<TR>");
out.println("<TD>" + co + "</TD>");
out.println("<TD>" + rs.getString("date_time")
+ "</TD>");
out.println("<TD>" + rs11.getString("title")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("url")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("updatecontent")
+ "</a></TD>");
%>
<td><input type="checkbox" class="case" name="case" id="chease"
value="<%=rs.getString("urlid")%>"></td>
<%
out.println("<TD><a href=\"Showupdate.jsp?urlid="
+ rs.getString("urlid") + "\" >VIEW </a></TD>");
}
%>
<%
out.println("</TD>");
out.println("</TR>");
co++;
}
out.println("</TABLE>");
if (co < 2) {
System.out.println("************" + co);
out.println("<center> NO UPDATES </center>");
}
out.print("</div");
} finally {
try {
conn.close();
} catch (SQLException se) {
}
}
%>
<br> Enter Email ID : <input type="text" class="textbox"
name="email"> <INPUT TYPE="SUBMIT" name="Operation"
onClick="document.pressed=this.value" VALUE="Send Email"> <br>
<br> <br> Click to View Selected Update Link... <INPUT
TYPE="SUBMIT" name="Operation" onClick="document.pressed=this.value"
VALUE="View">
</FORM>
<br> <br>
<div id="pageNavPosition" style="padding-top: 20px" align="center">
</div>
<br>
</center>
<script type="text/javascript"><!--
var pager = new Pager('tablepaging', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>
<%# include file="footer.jsp"%>
</body>
</html>
Better to use Apache POI and do one thing if you are not using maven download the below jars and keep it in your lib
dom4j-1.6.1.jar,
poi-3.9-20121203.jar,
poi-ooxml-3.9-20121203.jar,
poi-ooxml-schemas-3.9-20121203.jar,
xmlbeans-2.3.0.jar
and then using some classes you can read excel file even a row wise or cell wise
Try this I Hope this will you.....
Hope this helps`
public class ReadExcelfile {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Statement stmt = DriverManager.getConnection("jdbc:odbc:employee").createStatement();
ResultSet rs = stmt
.executeQuery("select lastname, firstname, id from [Sheet1$]");
while (rs.next()) {
String lname = rs.getString(1);
String fname = rs.getString(2);
int id = rs.getInt(3);
System.out.println(fname + " " + lname + " id : " + id);
}
rs.close();
stmt.close();
}
}
`

Add images to the form in java

I want to add the image and the file with the same form in JSP. how should i do it? Here, i made the form as:
<div id="user_img">
<form name="form1" method="post" enctype="multipart/form-data" action="image_user_upload_db.jsp">
<input type="file" name="poster" id="imagefile"/>
<input type="submit" id="submit_img" value="submit"/>
</form>
</div>
and the jsp page which help in saving the image is:
try{
String ImageFile="";
String itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart){
}
else{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try{
items = upload.parseRequest(request);
}
catch (FileUploadException e){
e.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext()){
FileItem item = (FileItem) itr.next();
if (item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
if(name.equals("poster")){
ImageFile=value;
}
}
else{
try{
itemName = item.getName();
File savedFile = new File(config.getServletContext().getRealPath("/")+"\\img\\user_img\\"+itemName);
item.write(savedFile);
}
catch (Exception e){
out.println("Error"+e.getMessage());
}
}
}
try{
String str="update user_info set img_name='"+itemName+"' where user_id=?";
PreparedStatement ps=con.prepareStatement(str);
ps.setInt(1,id1);
int rs1=ps.executeUpdate();
response.sendRedirect("profile.jsp");
}
catch(Exception el){
out.println("Inserting error"+el.getMessage());
}
}
}
I want this form to take the other input type also, but as i add another input type to the form, it gives error.
you can get their values take a closer look at this code
if (item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
if(name.equals("poster")){
ImageFile=value;
}
}
to get the other field values just use item.getFieldName() then check if it is the field name that you are looking for then store it in a variable
String otherField;
if(name.equals("otherField")){
otherField = item.getString();
}
Use the following code in your action page,
<%
String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile=config.getServletContext().getRealPath("/")+"user_upload\\"+saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
}
%>
Here 'user_upload' is a folder name, in which the uploaded file will be stored.
Before executing this code, you have to create a folder with the name 'user_upload' in your project directory.
NB:- You can change folder name.
use following code
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE); // sets maximum size of request (include file + form data)
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println("item.getFieldName() => "+item.getFieldName());
String fileAttr[] = fileName.split("\\.");
String newFileName = fileAttr[0];
int i = 1;
while (true) {
File f = new File(uploadPath + "\\" + newFileName + "." + fileAttr[1]);
if (f.exists()) {
newFileName = fileAttr[0] + i;
i++;
} else {
fileName = newFileName + "." + fileAttr[1];
break;
}
}
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message","Upload has been done successfully!");
} else {
System.out.println("1 item.getFieldName() => "+item.getFieldName());
if("description1".equalsIgnoreCase(item.getFieldName())){
//this part is for other field except file field
}
}
}
}

Categories