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());
Related
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.
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.
I am having a problem with my image upload code. When I try to use request.getParameter("title") from the form, the upload doesn't succeed. But when I remove the request.getParameter("title"), it works.
In short, how can I access other form fields? I want to store their values somewhere.
Here is my form:
<%# 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>Upload</title>
</head>
<body>
<div>
<form action="ImageUpload" method="POST" enctype="multipart/form-data"><br>
Title:<input type="text" name="title" id="title" /><br>
Reporter:<input type="text" name="reporter" id="reporter"><br>
Image:<input type="file" name="image" id="image" /><br>
<input type="submit" value="Upload">
</form>
</div>
</body>
</html>
The Upload Servlet:
package socialnewsreloaded.upload;
import java.io.IOException;
import java.io.InputStream;
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 org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.servlet.*;
/**
* Servlet implementation class ImageUpload
*/
#WebServlet("/ImageUpload")
#MultipartConfig
public class ImageUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
String title = request.getParameter("title");
response.getWriter().print(title);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iterate = upload.getItemIterator(request);
while (iterate.hasNext()) {
FileItemStream item = iterate.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
InputStream inStream = item.openStream();
byte[] b = new byte[inStream.available()];
inStream.read(b);
String value = new String(b);
//response.getWriter().print(fieldName+":"+value);
} else {
String path = "C:/uploads";
if (FileUpload.processFile(path, item)) {
response.getWriter().print(
"File Uploaded Successfully");
} else {
response.getWriter().print(
"Error Uploading File !!");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
}
FileUpload Class:
package socialnewsreloaded.upload;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
public class FileUpload {
public static boolean processFile(String path, FileItemStream stream)
throws IOException {
File file = new File(path + File.separator + "images");
if (!file.exists()) {
file.mkdir();
}
File savedFile = new File(file.getAbsolutePath() + File.separator
+ stream.getName());
try {
FileOutputStream outStream = new FileOutputStream(savedFile);
InputStream inStream = stream.openStream();
int i = 0;
byte[] b = new byte[1024];
while((i=inStream.read(b))!=-1){
outStream.write(b, 0, i);
}
outStream.flush();
outStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
It's the printing, not the getParameter("title"). You shouldn't produce any output until you've consumed all the input.
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.
I created a project inside the ofbiz/hot-deploy folder namely productionmgntSystem. Inside the folder ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem I created a .ftl file namely app_details_1.ftl.The following is the code of this file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT">
function uploadFile()
{
//alert("Before calling upload.jsp");
window.location='<#ofbizUrl>testing_service1</#ofbizUrl>'
}
</script>
</head>
<!-- <form action="<#ofbizUrl>testing_service1</#ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> -->
<form action="<#ofbizUrl>logout1</#ofbizUrl>" enctype="multipart/form-data" name="app_details_frm">
<center style="height: 299px; ">
<table border="0" style="height: 177px; width: 788px">
<tr style="height: 115px; ">
<td style="width: 103px; ">
<td style="width: 413px; "><h1>APPLICATION DETAILS</h1>
<td style="width: 55px; ">
</tr>
<tr>
<td style="width: 125px; ">Application name : </td>
<td>
<input name="app_name_txt" id="txt_1" value=" " />
</td>
</tr>
<tr>
<td style="width: 125px; ">Excell sheet : </td>
<td>
<input type="file" name="filename"/>
</td>
</tr>
<tr>
<td>
<!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> -->
<input type="submit" name="logout_cmd" value="logout"/>
</td>
<td>
<!-- <input type="submit" name="upload_cmd" value="Submit" /> -->
<input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/>
</td>
</tr>
</table>
</center>
</form>
</html>
the following coding is present in the file "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml"
......
.......
........
<request-map uri="testing_service1">
<security https="true" auth="true"/>
<event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/>
<response name="ok" type="view" value="ok_view"/>
<response name="exception" type="view" value="exception_view"/>
</request-map>
..........
............
..........
<view-map name="ok_view" type="ftl" page="ok_view.ftl"/>
<view-map name="exception_view" type="ftl" page="exception_view.ftl"/>
................
.............
.............
The following is the code in the file ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java
package org.ofbiz.productionmgntSystem.web_app_req;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WebServices1
{
public static String testingService(HttpServletRequest request, HttpServletResponse response)
{
//int i=0;
String result="ok";
System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start");
String contentType=request.getContentType();
System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType);
String str=new String();
// response.setContentType("text/html");
//PrintWriter writer;
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
{
System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)");
try
{
// writer=response.getWriter();
System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start");
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//this loop converting the uploaded file into byte code
while (totalBytesRead < formDataLength)
{
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
//for saving the file name
String 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;
//extracting the index of file
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;
//creating a new file with the same name and writing the content in new file
FileOutputStream fileOut = new FileOutputStream("/"+saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End");
}
catch(IOException ioe)
{
System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException");
//ioe.printStackTrace();
return("exception");
}
catch(Exception ex)
{
System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception");
return("exception");
}
}
else
{
System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part");
result="exception";
}
System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End");
return(result);
}
}
I want to upload a file to the server.The file is get from user <input type="file"..> tag in the app_details_1.ftl file & it is updated into the server by using the method testingService(HttpServletRequest request, HttpServletResponse response) in the class WebServices1. But the file is not uploaded.
I got the solution to my problem.I successfully upload the file into the server.This solution i get after the big fight with ofbiz.I made a little changes in my old coding.That is given below.
the following are the coding present in the "app_details_1.ftl"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!--<meta http-equiv="Content-Type" content="multipart/form-data; charset=ISO-8859-1">-->
<title>Insert title here</title>
<script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT">
function uploadFile()
{
//alert("Before calling upload.jsp");
window.location='<#ofbizUrl>testing_service1</#ofbizUrl>'
}
function logout1()
{
//alert("Logout1");
alert("<#ofbizUrl>logout1</#ofbizUrl>");
window.location='<#ofbizUrl>logout1</#ofbizUrl>'
}
</script>
</head>
<!-- <form action="<#ofbizUrl>testing_service1</#ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> -->
<body bgcolor="cyan">
<form enctype="multipart/form-data" action="<#ofbizUrl>uploadAttachFile</#ofbizUrl>" METHOD=POST>
<center style="height: 299px;">
<table border="0" style="height: 177px; width: 788px">
<tr style="height: 115px; ">
<td style="width: 103px; ">
<td style="width: 440px; "><h1>APPLICATION DETAILS</h1>
<td style="width: 55px; ">
</tr>
<tr>
<td style="width: 125px; ">Application name : </br></td>
<td>
<input name="app_name_txt" id="txt_1" value=" " />
</td>
<td></br></br></td>
</tr>
<tr>
<td style="width: 125px; ">Excell sheet : </td>
<td>
<input type="file" name="filename"/>
</td>
<td></br></br></td>
</tr>
<tr>
<td>
<td></br>
<td>
</tr>
<tr>
<td>
<input type="button" name="logout1_cmd" value="LOGOUT" onclick="logout1()"/>
<!-- <input type="submit" name="logout_cmd" value="logout"/>-->
</td>
<td>
<input type="submit" name="upload_cmd" value="UPLOAD" />
<!-- <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> -->
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
Here my main changes in the form action attribute.
The following are the coding snippet in "controller.xml"
...............
.............
<request-map uri="uploadAttachFile">
<security https="true" auth="true"/>
<!-- <event type="simple" invoke="createCommunicationContent" path="component://productionmgntSystem/script/org/ofbiz/productionmgntSystem/CommunicationEventEvents.xml"/> -->
<event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.Uploading" invoke="uploadFile"/>
<response name="AttachementSuccess" type="view" value="AttachementSuccess"/>
<response name="AttachementException" type="view" value="AttachementException"/>
</request-map>
................
.....................
<view-map name="AttachmentError" type="ftl" page="file_attach_error.ftl"/>
<view-map name="AttachementException" type="ftl" page="file_attach_error.ftl"/>
<view-map name="AttachementSuccess" type="ftl" page="AttachementSuccess.ftl"/>
...........
............
Here i should map a request "uploadAttachFile" to the event "uploadFile".That is this event call the method "uploadFile" inside the class "org.ofbiz.productionmgntSystem.web_app_req.Uploading".This class is defined by me.Actually file uplaod is there in ofbiz i just copy the coding & altered some changes for my application.
Inside the method "uploadFile" is i write the coding for uploading the file into server.
I stored the class "org.ofbiz.productionmgntSystem.web_app_req.Uploading" in the following folder "ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req". Here the "productionmgntSystem" is the my application name.
The following are coding present inside the class "org.ofbiz.productionmgntSystem.web_app_req.Uploading"
//UPLOADING A CONTENT TO THE SERVER
package org.ofbiz.productionmgntSystem.web_app_req;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ofbiz.service.ServiceUtil;
import java.util.List;
public class Uploading
{
public static String uploadFile(HttpServletRequest request,HttpServletResponse response)
{
//ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp"))); //Creation of servletfileupload
System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - start\n\t");
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory()); //Creation of servletfileupload
java.util.List lst = null;
String result="AttachementException";
String file_name="";
try
{
lst = fu.parseRequest(request);
}
catch (FileUploadException fup_ex)
{
System.out.println("\n\n\t****************************************\n\tException of FileUploadException \n\t");
fup_ex.printStackTrace();
result="AttachementException";
return(result);
}
if(lst.size()==0) //There is no item in lst
{
System.out.println("\n\n\t****************************************\n\tLst count is 0 \n\t");
result="AttachementException";
return(result);
}
FileItem file_item = null;
FileItem selected_file_item=null;
//Checking for form fields - Start
for (int i=0; i < lst.size(); i++)
{
file_item=(FileItem)lst.get(i);
String fieldName = file_item.getFieldName();
//Check for the attributes for user selected file - Start
if(fieldName.equals("filename"))
{
selected_file_item=file_item;
//String file_name=file_item.getString();
//file_name=request.getParameter("filename");
file_name=file_item.getName(); //Getting the file name
System.out.println("\n\n\t****************************************\n\tThe selected file item's file name is : "+file_name+"\n\t");
break;
}
//Check for the attributes for user selected file - End
}
//Checking for form fields - End
//Uploading the file content - Start
if(selected_file_item==null) //If selected file item is null
{
System.out.println("\n\n\t****************************************\n\tThe selected file item is null\n\t");
result="AttachementException";
return(result);
}
byte[] file_bytes=selected_file_item.get();
byte[] extract_bytes=new byte[file_bytes.length];
for(int l=0;l<file_bytes.length;l++)
extract_bytes[l]=file_bytes[l];
//ByteBuffer byteWrap=ByteBuffer.wrap(file_bytes);
//byte[] extract_bytes;
//byteWrap.get(extract_bytes);
//System.out.println("\n\n\t****************************************\n\tExtract succeeded :content are : \n\t");
if(extract_bytes==null)
{
System.out.println("\n\n\t****************************************\n\tExtract bytes is null\n\t");
result="AttachementException";
return(result);
}
/*
for(int k=0;k<extract_bytes.length;k++)
System.out.print((char)extract_bytes[k]);
*/
//String target_file_name="/hot-deploy/productionmgntSystem"
//Creation & writing to the file in server - Start
try
{
FileOutputStream fout=new FileOutputStream(file_name);
System.out.println("\n\n\t****************************************\n\tAfter creating outputstream");
fout.flush();
fout.write(extract_bytes);
fout.flush();
fout.close();
}
catch(IOException ioe_ex)
{
System.out.println("\n\n\t****************************************\n\tIOException occured on file writing");
ioe_ex.printStackTrace();
result="AttachementException";
return(result);
}
//Creation & writing to the file in server - End
System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - end\n\t");
return("AttachementSuccess");
//Uploading the file content - End
}
}
Now in my application im able to upload the file into the server.
If you don't want to write in ftl and want to write it in a simple form, here is my code. but First let me thank SIVAKUMAR.J for putting me on the right track.
Here is the form's code:
<form name="ImportBulkAttendance" target="uploadFileJava" type="upload" default-map-name="content" focus-field-name="contentTypeId" header-row-style="header-row" default-table-style="basic-table">
<field name="filename" title="filename">
<file name="filename"/>
</field>
<field name="createButton">
<submit button-type="button" />
</field>
</form>
Then in controller.xml
<request-map uri="uploadFileJava">
<security https="true" auth="true"/>
<event type="java" path="com.ofbiz.attendance.Uploading" invoke="uploadFile"/>
</request-map>
<view-map name="AttachmentError" type="screen" page="component://yourComponentName/widget/yourComponentNameScreens.xml#main"/>
create ant missing folder in this path in your project: yourComponentFolder/src/ofbiz/attendance/
then create Uploading.java
package com.ofbiz.attendance;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ofbiz.service.ServiceUtil;
import java.util.List;
public class Uploading
{
public static String uploadFile(HttpServletRequest request,HttpServletResponse response)
{
//ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp"))); //Creation of servletfileupload
System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - start\n\t");
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory()); //Creation of servletfileupload
java.util.List lst = null;
String result="AttachementException";
String file_name="";
try
{
lst = fu.parseRequest(request);
}
catch (FileUploadException fup_ex)
{
System.out.println("\n\n\t****************************************\n\tException of FileUploadException \n\t");
fup_ex.printStackTrace();
result="AttachementException";
return(result);
}
if(lst.size()==0) //There is no item in lst
{
System.out.println("\n\n\t****************************************\n\tLst count is 0 \n\t");
result="AttachementException";
return(result);
}
FileItem file_item = null;
FileItem selected_file_item=null;
//Checking for form fields - Start
for (int i=0; i < lst.size(); i++)
{
file_item=(FileItem)lst.get(i);
String fieldName = file_item.getFieldName();
//Check for the attributes for user selected file - Start
if(fieldName.equals("filename"))
{
selected_file_item=file_item;
//String file_name=file_item.getString();
//file_name=request.getParameter("filename");
file_name=file_item.getName(); //Getting the file name
System.out.println("\n\n\t****************************************\n\tThe selected file item's file name is : "+file_name+"\n\t");
break;
}
//Check for the attributes for user selected file - End
}
//Checking for form fields - End
//Uploading the file content - Start
if(selected_file_item==null) //If selected file item is null
{
System.out.println("\n\n\t****************************************\n\tThe selected file item is null\n\t");
result="AttachementException";
return(result);
}
byte[] file_bytes=selected_file_item.get();
byte[] extract_bytes=new byte[file_bytes.length];
for(int l=0;l<file_bytes.length;l++)
extract_bytes[l]=file_bytes[l];
//ByteBuffer byteWrap=ByteBuffer.wrap(file_bytes);
//byte[] extract_bytes;
//byteWrap.get(extract_bytes);
//System.out.println("\n\n\t****************************************\n\tExtract succeeded :content are : \n\t");
if(extract_bytes==null)
{
System.out.println("\n\n\t****************************************\n\tExtract bytes is null\n\t");
result="AttachementException";
return(result);
}
/*
for(int k=0;k<extract_bytes.length;k++)
System.out.print((char)extract_bytes[k]);
*/
//String target_file_name="/hot-deploy/productionmgntSystem"
//Creation & writing to the file in server - Start
try
{
FileOutputStream fout=new FileOutputStream(file_name);
System.out.println("\n\n\t****************************************\n\tAfter creating outputstream");
fout.flush();
fout.write(extract_bytes);
fout.flush();
fout.close();
}
catch(IOException ioe_ex)
{
System.out.println("\n\n\t****************************************\n\tIOException occured on file writing");
ioe_ex.printStackTrace();
result="AttachementException";
return(result);
}
//Creation & writing to the file in server - End
System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - end\n\t");
return("AttachementSuccess");
//Uploading the file content - End
}
}
That's it copy the files with the same name and they should work directly :) I hope this saves someone's time.
N.B. You don't need to create an XML service.