Upload PDF file in JSP page and convert it to text file - java

I need some help with my code.. I have a working Java code to convert PDF to Text file and a JSP page which uploads it.
The thing is I want to link them i.e., when I upload a PDF file it should take the file uploaded as input and generate corresponding converted text file.
FileConverter.java
package fileconverter;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.IOException;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
public class FileConverter {
public static void main(String[] args) {
selectPDFFiles();
}
//allow pdf files selection for converting
public static void selectPDFFiles(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF","pdf");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File[] Files=chooser.getSelectedFiles();
System.out.println("Please wait...");
for( int i=0;i<Files.length;i++){
convertPDFToText(Files[i].toString(),"Text-File"+i+".txt");
}
System.out.println("Conversion complete");
}
}
public static void convertPDFToText(String src,String desc){
try{
FileWriter fw=new FileWriter(desc);
try (
BufferedWriter bw = new BufferedWriter(fw)) {
PdfReader pr=new PdfReader(src);
int pNum=pr.getNumberOfPages();
for(int page=1;page<=pNum;page++){
String text=PdfTextExtractor.getTextFromPage(pr, page);
bw.write(text);
bw.newLine();
}
bw.flush();
}
}
catch(IOException e){}
}
}
upload.jsp
<%--
Document : upload
Created on : May 16, 2014, 1:42:47 PM
Author : Kelvin
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head><title>Upload and convert</title>
<body>
<div id="main">
<table id="uploadtbl" width="550" align="center" border="1">
<tr>
<th align="center">Upload and convert pdf to text file</th>
</tr>
<tr>
<td>
<input type="file" name="upload">
</td>
</tr>
<tr>
<td><input type="submit" name="totext" value="Convert To Text" /></td>
</tr>
</table>
</div>
</body>
</html>

Generally you have to create HTML form that sends file to your server using POST method, i.e. something like this:
<form action="/upload" method="POST">
<input type="file" name="upload">
<input type="submit" value="send">
<form>
Now you need server side. You can implement your own servlet (or JSP although it is not recommended to implement code into JSP) and deploy it under URL "/upload". The name of URL does not matter, it just must correspond to what you write in action attribute of your form.
However you do not have to implement servlet. Just take it from apache. I hope this helps.

Related

How to write to a file in Java using Servlet [duplicate]

This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Closed 5 years ago.
I am creating a Java Web Application which takes data from a HTML form and saves it to a text file using a Servlet. However when I run the application I cannot see the text file anywhere so I am unsure if it was created successfully or not. Does anyone have any ideas why the file is not appearing?
Here is my code for the HTML form:
<html>
<head>
<title>Register Customer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name = "regcustomer" method = "get" action = "CustomerServlet" >
Customer Name
<input type="text" name="customerName"> <br>
Customer Address
<input type="text" name="customerAddress"> <br>
Telephone Number
<input type="text" name="telNo"> <br>
Email
<input type="text" name="email"> <br>
Cost per KG shipped
<input type="text" name="costPKG"> <br>
<input type="submit" value="Register"> <br> <br>
Back
</form>
</body>
And here is my code for the servlet:
package Servlets;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomerServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
String customerName;
customerName = request.getParameter("customerName");
String customerAddress = request.getParameter("customerAddress");
String telNo;
telNo = request.getParameter("telNo");
String email = request.getParameter("email");
String costPKG = request.getParameter("costPKG");
try{
File file = new File("C:/xyz.txt");
FileWriter fstream = new FileWriter(file,true);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(customerName+" "+customerAddress+" "+telNo+" "+email+"
"+costPKG);
out.newLine();
}
pw.println("File is created successfully");
}
catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any suggestions would be much appreciated
Try adding the line:
#WebServlet(urlPatterns = { "/CustomerServlet" })
before:
public class CustomerServlet extends HttpServlet {
Note: If you are using old container (not implemented Servlet 3.0, like Tomcat 6.0), then you have to edit web.xml.

Calling Java method from JSP not wotking

I am trying to call a java method('method1') that runs some r code(using RCaller) when a specific button is clicked on a JSP page('button1'), but when i click on the button it doesn't do anything and I am getting no errors in the output. I'm trying to use a servlet to run the java method from a JSP file. I'd appreciate any help.
Analysis.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Analysis Page</title>
</head>
<body>
<center><h2>
Final year Prototype
</h2></center>
<center> <table border="0">
<thead>
<tr>
<th>Disabilities Analysis</th>
</tr>
</thead>
<tbody>
<tr>
<center><td></td></center>
</tr>
<tr>
<td>
<center>
Current HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
New HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
<form action="${pageContext.request.contextPath}/myservlet" method="POST">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
</center>
</td>
</tr>
<tr>
<td>
<center>
Return
</center>
</td>
</tr>
</tbody>
</table></center>
</body>
</html>
myServlet.java:
package webJava;
import java.io.IOException;
import java.io.PrintWriter;
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("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TestMethods t = new TestMethods();
String button = request.getParameter("button");
if ("button1".equals(button)) {
t.method1();
} else if ("button2".equals(button)) {
t.method2();
} else if ("button3".equals(button)) {
t.method3();
} else {
}
request.getRequestDispatcher("/Analysis.jsp").forward(request, response);
}
}
TestMethods.java:
package webJava;
import java.io.File;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
public class TestMethods {
public void method1() {
try {
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("/Library/Frameworks/R.framework/Versions/3.3/Resources/Rscript");
caller.cleanRCode();
caller.setRCode(code);
// load the ggplot2 library into R
code.R_require("ggplot2");
// create a data frame in R using x and y variables
code.addRCode("df <- data.frame(x,y)");
// plot the relationship between x and y
File file = code.startPlot();
code.addRCode("ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method='lm') + ggtitle('y = f(x)')");
caller.runOnly();
ImageIcon ii = code.getPlot(file);
code.showPlot(file);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void method2() {
//some code
}
public void method3() {
//some code
}
}
My project directory:
Screenshot

Sending multipart encryption data using dropzone

Here is my index.html:
<%# 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">
<script src="extra/js/jquery-1.10.2.min.js"></script>
<script src="extra/downloads/dropzone.js"></script>
<script>
$(document).ready(function()
{
var myDropzone = new Dropzone("div#my-awesome-dropzone", {url:'UploadServlet'});
Dropzone.autoDiscover = false;
myDropzone.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
$("#button").click(function(){
var source = $("#my-awesome-dropzone").attr("src");
alert(source);
});
});
</script>
<link rel="stylesheet" href="extra/downloads/css/dropzone.css" type="text/css">
<title>Insert title here</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data" >
<table id="table">
<tr>
<td> Unique ID : </td>
<td><input type="text" id="unique" name="unique" maxlength="6" required></input></td>
</tr>
<tr>
<td> Name : </td>
<td><input type="text" id="fullname" name="fullname" maxlength="255" required></input></td>
</tr>
<tr>
<td> Age : </td>
<td><input type="text" id="age" name="age" maxlength="255" required></input></td>
</tr>
<tr>
<td> Address : </td>
<td><input type="text" id="address" name="address" maxlength="255" required></input></td>
</tr>
<tr>
<td> Phone_number </td>
<td><input type="text" id="phonenumber" name="phonenumber" maxlength="10" required></input></td>
</tr>
</table>
<div id="my-awesome-dropzone" class="dropzone"></div>
<div>
<input type="submit" value="Submit data and files!"></input>
</div>
</form>
</body>
</html>
And this my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dropzone;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
public class UploadServlet extends HttpServlet {
private String fileSavePath;
private static final String UPLOAD_DIRECTORY = "upload";
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
Connection con = null;
List<FileItem> items;
try {
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 e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
String uid = request.getParameter("unique");
String fullname = request.getParameter("fullname");
System.out.println(fullname);
String age = request.getParameter("age");
String address = request.getParameter("address");
String phonenumber = request.getParameter("phonenumber");*/
String path = null;
String message = null;
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dropzone", "root", "root");
String sql = "INSERT INTO details(u_id,name,age,address,phonenumber,path) values(?,?,?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
//##########################################################?//
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
//##################################################################//
statement.setString(1,"uid");
statement.setString(2,"fullname");
statement.setString(3,"age");
statement.setString(4,"address");
statement.setString(5,"phonenumber");
statement.setString(6,"path");
int row = statement.executeUpdate();
if(row>0){
message = "Contact saved";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "ERROR: " +e.getMessage();
}
finally
{
if(con !=null)
{
try{
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
System.out.println(message);
request.setAttribute("Message",message);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
}
Here is screenshot of the error:
I want to use the dropzone for uploading images.But if I use multipart/form-data for the form, the fields except the images give null values. I tried using the simple getParameter method. But it doesnt seem to work. Also I tried using Lists but it gives an error. Anyone tried dropzone with jsp?? Help
This is happening because you are not treating the whole form as dropzone but you are treating only the #my-awesome-dropzone div as dropzone .That won't work if you want to submit whole form with the files on one click.
1)In the form tag add an id say id="mydropzone" and class class="dropzone"
<form action="UploadServlet" id="mydropzone" class="dropzone" method="post" enctype="multipart/form-data" >
2)Remove the div from your code which has the id id="my-awesome-dropzone".Then Add a new div to show the files uploaded in drag and drop
<div id="dropzonePreview"></div>
3)add an id to your submit button
<input type="submit" id="sbmtbtn" value="Submit data and files!" />
4)now add this script
<script>
Dropzone.options.mydropzone = {
// url does not has to be written if we have wrote action in the form tag but i have mentioned here just for convenience sake
addRemoveLinks: true,
autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
autoDiscover: false,
paramName: 'pic', // this is similar to giving name to the input type file like <input type="file" name="pic" />
previewsContainer: '#dropzonePreview', // we specify on which div id we must show the files
clickable: false, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable
accept: function(file, done) {
console.log("uploaded");
done();
},
error: function(file, msg){
alert(msg);
},
init: function() {
var myDropzone = this;
//now we will submit the form when the button is clicked
document.getElementById("sbmtbtn").onclick = function(e) {
e.preventDefault(); //this will prevent the default behaviour of submit button because we want dropzone to submit the form
myDropzone.processQueue(); // this will submit your form to the specified action which directs to your jsp upload code
// after this, your whole form will get submitted with all the inputs + your files and the jsp code will remain as usual
//REMEMBER you DON'T have to call ajax or anything by yourself to submit the inputs, dropzone will take care of that
};
} // init end
};
</script>
NOTE :
YOU DO NOT have to write any extra code to make the form submit .
After writing the above code just follow your normal flow to upload
file in jsp like writing the xml and writing the servlet class and fetch all the inputs and files there.
Remember dropzone uses ajax to upload so the form will not be
refreshed when you click submit.
You cannot click on the form to upload files now you have to just
drag the files in the form.

Getting value from combobox to servlet in jsp

I have problem with get a value from combobox in my .jsp file to servlet.
I use method request.getParameter i other servlets and it works. In this class it don't.
I was also trying to get value from text field to this servlet but also don't work. I don't have any idea how to solve this problem.
I have combobox like that:
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
I'm tring to get value:
String folder = request.getParameter("folders1");
My jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<%# page import="tools.User" %>
<%# page import="java.io.File" %>
<%# page import="java.text.DecimalFormat" %>
<%#page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Serwer dysku sieciowego </title>
</head>
<body>
<div class="container">
<div class="ramka_zaproszenie">
<%
File[] listOfFolders;
User user;
String username;
String status = null;
if(session.getAttribute("user")!=null){
user = (User)session.getAttribute("user");
username = user.getLogin();
status = user.getType().toString();
} else {
username = "unknown";
}
%>
<p class="loguj">Witaj, <%= username %>!</p><br>
<% if(session.getAttribute("user")!=null){ %>
<p class="tekst">Wrzuc plik na serwer:</p>
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
<form action="folder" method="get">
<p class="tekst"> Folder: <br><input class="pole" id="Folder" type="text" name="folderName" />
<br /></p>
<input class="zatwierdz" type="submit" id="submit" value="Utwórz" /><br>
</form>
<br />
<% if(status.equalsIgnoreCase("ADMIN")){ %>
<a class="wroc" href="zmiana_rozmiaru.jsp">Zmiana Pojemnosci</a>
<%}%>
<br />
<br />
<p class="tekst">Posiadane pliki na serwerze:</p>
<form method="post">
Folder:
<select name="folders">
<option value=0 selected="selected" >Wybierz folder</option>
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
<input type="submit" value="Wybierz"><br>
</form>
<br />
Pliki z folderu: <%=request.getParameter("folders")%>
<center><table id="tabela">
<tr class="alt">
<th>Nazwa</th>
<th>Rozmiar</th>
<th>Pobierz</th>
<th>Usun</th>
</tr>
<%
System.out.println(request.getParameter("folders"));
user = (User)session.getAttribute("user");
File[] listOfFiles = user.listOfFiles(request.getParameter("folders"));
if(listOfFiles != null){
for(File file : listOfFiles){
DecimalFormat twoDForm = new DecimalFormat("#.##");
out.print("<tr class=\"alt\"><td>" + file.getName()+"</td><td>" +twoDForm.format((double)file.length()/1024.0)+" KB</td><td align=center> <img border=\"0\" src=\"downloadsmall.png\"></td><td align=center><a src=\"deletesmall.png\" href=\"delete?filePath="+file.getAbsolutePath()+"\" ><img border=\"0\" src=\"deletesmall.png\"></a></td></tr>");
}
}
%>
</table>
</center><br>
<form action="logout" method="post">
<input type="image" src="wylacznik.png" id="submit">
</form>
<br><br>
<%
if (session.getAttribute("warning") != null) {
%>
<span><%= session.getAttribute("warning") %></span>
<%
session.removeAttribute("warning");
}
%>
<% } %>
<div class="footer">Copyright 2013 by JavaProjectTeam.</div>
</div>
</div>
</body>
</html>
And my servlet file
<pre>package servlets;
import java.io.*;
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.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import tools.Connector;
import tools.User;
#WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private File file ;
public void init(){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
request.setCharacterEncoding("UTF-8");
String folder = request.getParameter("folders1");
HttpSession session = request.getSession(true);
User user = (User)session.getAttribute("user");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
session.setAttribute("warning", "Nie masz zadnych plikow");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(user.getSpace() * 1024);
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write(file);
System.out.println(file.getName());
try{
Connection connection = new Connector().getConnection();
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator('.');
DecimalFormat twoDForm = new DecimalFormat("#.##", otherSymbols);
System.out.println(twoDForm.format((double)file.length()/1024.0));
connection.createStatement().executeUpdate("UPDATE `users` SET `space` = `space`-"+twoDForm.format((double)file.length()/1024.0)+" where id="+user.getId());
} catch(SQLException e){
e.printStackTrace();
}
session.setAttribute("warning", "Plik został dodany do wirtualnego dysku.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
session.setAttribute("warning", "File is too big! Only "+user.getSpace()+"KB left.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}<code>
It's because you're sending a multipart/form-data request while that's by default not supported by servlets. I however notice that you're still using the "legacy" Apache Commons FileUpload to obtain the uploaded file instead of new Servlet 3.0 provided HttpServletRequest#getPart(). In that case, you've basically 2 options:
Stick to Commons FileUpload. You should be collecting regular form fields in the else block of your if (!fi.isFormField()) which you're currently completely ignoring.
if (!fi.isFormField()) {
// Collect uploaded file from fi.
} else {
// Collect normal form field from fi.
}
Get rid of Commons FileUpload and use #MultipartConfig annotation.
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
This way you can get files by request.getPart() and keep using request.getParameter() the usual way for regular form fields.
See also:
How to upload files to server using JSP/Servlet?
Unrelared to the concrete problem, that's not a combobox, but that's a dropdown. A combobox is an editable dropdown. Further, writing Java code in JSP is a bad practice. Java code belongs in Java classes like a servlet. To loop over options, use JSTL <c:forEach>. And, writing HTML code in a Java class like a servlet is a bad practice. HTML code belongs in a JSP file. Use RequestDispatcher#forward() to present results in a JSP. See further also our servlets wiki page.
Oh, you've a major threadsafety problem in your servlet. There's only one instance of a servlet during applications lifetime which is shared across all HTTP requests. Those fields
private boolean isMultipart;
private String filePath;
private File file ;
would be shared across all HTTP requests resulting in potential major problems when multiple users concurrently use the same servlet at the same moment. Get rid of them and move them to inside the doXxx() method block.

unable to get path to read .xls file

i am developing a .xls reader who take .xls file and read that,, and give the output as plain text
but i am facing some problem to get the file path into the servlet ... i am using poi.jar to read the .xls file ..
.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Upload Form</title>
</head>
<body bgcolor="lightblue">
<table id='table1' align="center" >
<tr>
</tr></table><br/><br/><br/>
<br/>
<table border="1" width="50%" bgcolor="#C2DFFF">
<tr>
<td width="100%">
<form action="writeExcel" method="post" enctype="multipart/form-data">
<h2 align="center">Welcome</h2>
<center>
<input type="file" name="photo"/>
<input type="file" name="hem"/>
<br/><br/>
<input type="submit" value="Save"/>
<input type="button" value="Logout" name="logout" onclick="goToURL();" />
<br/>
<br/>
</center>
</form>
</td>
</tr>
</table>
<br/><br/>
</body>
</html>
.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class writeExcel extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String fileName = request.getParameter("hem");
Vector dataHolder = ReadCSV(fileName);
printCellDataToConsole(dataHolder);
}
public static Vector ReadCSV(String fileName) {
Vector cellVectorHolder = new Vector();
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
return cellVectorHolder;
}
private static void printCellDataToConsole(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
String stringCellValue = myCell.toString();
System.out.print(stringCellValue + "\t");
}
System.out.println();
}
}
}
#AVD : Does fileName represent an absolute path of file/doc? If not then set/obtain real (absolute) path.
#Nitin Sharma: thank you AVD.. when i am using finename="C:\a.xls" is working fine But i am trying to take path from .jsp through file , it gives only file name not full path
#AVD : You have to save the uploaded file under your web-app root (or subfolder) or use InputStream (Servlet 3.0 Part or Apache fileupload api) object of uploaded file instead of fileName.
#Nitin Sharma : i don't want to upload file ... i just want to get full path of that file ..
#AVD : There is nothing left to say! There is no choice. (Do not save the uploaded file instead use the stream of uploaded file).
#Nitin Sharma: i used that but poi use File class object to read the file.. but Apache fileupload api use FileItem class object to read or get the path of the .xls file... and i am not able to typecast FileItem to File
Take a look at POIFSFileSystem class, it takes InputStream parameter and you may obtain via FileItem.getInputStream() (Commons upload).
POIFSFileSystem myFileSystem = new POIFSFileSystem(fileItem.getInputStream());

Categories