How to write output continous row from servlet - java

I am working on JSP and servlet.
Code below works, but I want it to be more dynamic.
Here's my JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form ACTION="Servlet" method="POST">
<body><h1>Data Mahasiswa</h1>
<table>
<tr><td>Nama </td>
<td>: <input type="text" name="Name" value="" /></td>
</tr>
<tr><td>NIM </td>
<td>: <input type="text" name="ID" value="" /></td>
</tr>
<tr><td>Progdi </td>
<td>: <input type="radio" name="Member" value="Not Member" />Not Member
<input type="radio" name="Member" value="Member" />Member
</td>
</tr>
</table>
<input type="submit" value="SAVE" />
</form>
</body>
</html>
And here's my Servlet
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet extends HttpServlet {
private String temp;
private BufferedWriter writer;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("Name");
String s2 = request.getParameter("ID");
String s3 = request.getParameter("Member");
try{
try {
String text = (s1 + " | " + s2 + " | " + s3);
File file = new File("D:/write.txt");
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
finally{
out.println("<h1> Data Saved <h1>");
}
}
And I'd like to make my output write.txt as below
Bill | 788878 | Member
Mark | 655598 | Member
Ron | 953116 | Not Member
Current code only works for 1 row only.
What I mean is, every re-entry input data, they would be written on next row on output txt file.

Please try
writer = new BufferedWriter(new FileWriter(file, true));.
The extra true specifies that the write mode is append, not over write
append - boolean if true, then data will be written to the end of the
file rather than the beginning.

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.

File or Image uploading using Java Servlet with Apache Commons Library

Here is my Code index.jsp
<%--
Document : index
Created on : 14 Feb, 2012, 4:46:05 AM
Author : Sanjib Narzary
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="/CBKD_WEB/img" method="post"
enctype="multipart/form-data"
name="productForm" id="productForm"><br><br>
<table width="400px" align="center" border=0
style="background-color:ffeeff;">
<tr>
<td align="center" colspan=2 style=" font-weight:bold;font-size:20pt;">
Image Details
</td>
</tr>
<tr>
<td align="center" colspan=2> </td>
</tr>
<tr>
<td>Image Link: </td>
<td>
<input type="file" name="file" id="file">
<td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
</body>
</html>
and Servlet img.java
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.*;
public class img extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(
request);
System.out.println("request: " + request);
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(img.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("items: " + items);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
System.out.println("name: " + name);
String value = item.getString();
System.out.println("value: " + value);
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-"
+ itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: " + domainName);
String finalimage = buffer.toString() + "_" + r + domainName;
System.out.println("Final Image===" + finalimage);
File savedFile = new File("E:/sanjib/" + "temp/" + finalimage);
item.write(savedFile);
out.println("<html>");
out.println("<body>");
out.println("<table><tr><td>");
out.println("<img src=images/" + finalimage + ">");
out.println("</td></tr></table>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
}
}
}
}
}
}
This code is fine and working without any error in Netbeans Web Application with Glassfish 3.1 Server. But what my problem is if i try to upload the image it is showing Alert in Firefox like The connection to the server was reset while the page was loading and in Google Chrome This Error
This web page is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this web page later.
Check your Internet connection. Reboot any routers, modems or other network devices that you may be using.
Add Google Chrome as a permitted programme in your firewall or antivirus software's settings. If it is already a permitted programme, try deleting it from the list of permitted programmes and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure that the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the spanner menu > Options > Under the Bonnet > Change proxy settings... > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox.
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.

How to Upload a file from client to server using OFBIZ?

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.

Categories