how to upload excel sheet in servlet using browser - java

I want to upload my excel sheet in my local system using servlet API but i am getting exception
java.io.FileNotFoundException: D:\Core-Java_Eclipse.metadata.plugins
\org.eclipse.wst.server.core\tmp0\wtpwebapps\UploadMenu\uploaded (Access is denied)
here i am using two jar 1. commons-fileupload-1.2.1.jar 2. commons-io-1.4.jar
i dont want to use third party implementation jar
Please see my code which is written in servlet
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String ctxPath=request.getRealPath("/");
File dir=new File(ctxPath,"uploaded");
if(!dir.exists()){
dir.mkdir();
}
Writer out=response.getWriter();
boolean uploadData=ServletFileUpload.isMultipartContent(request);
if(uploadData){
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*10);
factory.setRepository(new File("c:\\temp"));
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setSizeMax(1024*1024*50);
try{
List<FileItem> fileItems=upload.parseRequest(request);
Iterator<FileItem> i=fileItems.iterator();
while(i.hasNext()){
FileItem fi=i.next();
if(!fi.isFormField()){
String fieldName=fi.getFieldName();
String fileName=fi.getName();
String contentType=fi.getContentType();
boolean isInMemory=fi.isInMemory();
long sizeInByte=fi.getSize();
StringTokenizer tok=new
StringTokenizer(fileName,"/");
String fileToWrite="";
while(tok.hasMoreTokens()){
fileToWrite=tok.nextToken();
}
File file=new File(dir,fileToWrite);
fi.write(file);
}
}
}catch(Exception e){
e.printStackTrace();
}
out.write("<h1>File Uploaded in <br/>"+dir.getAbsolutePath());
}else{
out.write("No File Uploaded");
}
}
}
please tell me how to resolve my problem and how to upload this file is user
define directry means (D:// menu) folder
thanx is Advance

Related

Java HTTPClient File Upload Server

edit: solved below
So I need to create a server that can be used to upload files to and then serve those files back upon request. After some research it seemed like using HttpClient on the client side and FileUpload on the server side with a Tomcat servlet would be a good way to accomplish this task. After pulling from various example sources I have come up with the following code for the client:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
public class Client {
static String url = "http://localhost:8080";
public static void main(String[] args) throws Exception {
File file = new File("2048.zip");
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
HttpEntity entity = builder.build();
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
try {
client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
//list_files();
}
}
And this for the servlet code:
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root);
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This in the web-xml:
<servlet>
<servlet-name>fileservlet</servlet-name>
<servlet-class>servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileservlet</servlet-name>
<url-pattern>/fileservlet</url-pattern>
</servlet-mapping>
When I try to run the client I just get hit with these errors until it times out.
Dec 04, 2017 4:08:34 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:8080: Connection reset by peer: socket write error
Dec 04, 2017 4:08:34 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->http://localhost:8080
This is my first time working with servlets and Tomcat so I'm unsure if there's a configuration issue in eclipse or an actual issue with the code.
Edit: Okay so for the first time I've managed to get the file to send through the client and be saved by the server. The first thing I had to do was ensure that the "url" matched the correct servlet extension. When I launched the servlet in eclipse it automatically opened http://localhost:8080/FileServlet/FileServlet so this is what I used in the client when sending the file. I also uncommented a part of the servers.xml file having to do with thread pool.
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
Also I used the code straight from the HttpClient example page for multipart sending.

Uploading a file and Appending its contents to an EXISTING text file

I want to copy the contents of an uploaded file to a text file on my local.
The important thing is- I already have a file on my system named "Data" and I want to append the contents of uploaded file in "Data".
I have successfully copied the contents of the uploaded file but facing issue in appending the data.
Below is my Servlet file:
package pack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "D:/Data Repository.txt";
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//process only if its multipart content
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
item.write(new File(UPLOAD_DIRECTORY));
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex)
{
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Can something be added or modified in the below statement so that it would append the data to the existing file rather than creating a new file every time and copying its content?
item.write(new File(UPLOAD_DIRECTORY));

java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet

I want to implement a servlet and call it in a WebApp.
I am constantly get java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet from the Apache Tomcat Server. I made sure my class extends HttpServlet this is my code:
package Servlet;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.telnet.TelnetClient;
public class Servlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
TelnetClient telnet = new TelnetClient();
telnet.connect(request.getParameter("router"), 23);
PrintStream output = new PrintStream(telnet.getOutputStream());
output.println(request.getParameter("login"));
output.flush();
output.println(request.getParameter("password"));
output.flush();
out.printf("SUCCESS");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
out.printf("ERROR");
}
}
I renamed the package and the class and it works perfectly.

NullPointerException on Apache Server Servlet using JPA

Im trying to display contents of table (test_dept) which is in SQLSERVER
I have created a connection profile also.
I have written a Servlet like below... But Im getting this error.
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
//import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = "/ServletClient")
public class ServletClient extends HttpServlet
{
#PersistenceUnit
EntityManagerFactory factory;
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
//ServletOutputStream out = resp.getOutputStream();
PrintWriter pw = resp.getWriter();
java.util.List list = factory.createEntityManager().createQuery("select f from test_dept f;").getResultList();
pw.println("<html><body bgcolor=silver text=green><table>");
for (Object tdp : list)
{
pw.println("In The Loop");
pw.println("<tr><td>" + ((TestDept) tdp).getDptnam() + "</td></tr>");
}
pw.println("</table>");
pw.println("<font size=35><b>List created AdapChain</b></font>");
pw.println("</body></html>");
}
}
I don't think any version of Apache Tomcat supports injection of EntityManager or EntityManagerFactory objects out of the box.
You need to choose a server platform that supports more of the JavaEE specification.

Generate PDF file in an appropriate format

For my use, I created a PDF file using flying-saucer library. It was a legacy HTML so I cleaned out the XHTML using HTMLCleaner library.
After this I serialize the XML as string then pass it to the iText module of flying-saucer to render it and subsequently create the PDF.
This PDF I place it in the OutputStream. After the response is committed I get a dialog asking to save or open it. However it does not get saved as PDF file. I have to right-click and open it in Adobe or any PDF reader.
How do I make it display in the PDF reader. And make the file be saved as .pdf file. What would be an effective and user-friendly way to handle this issue? Help as always will be greatly appreciated!
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XmlSerializer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
public class MyPDF extends HttpServlet {
public MyPDF() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
String html = request.getParameter("source");
try
{
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
TagNode node = cleaner.clean(html);
//String content = "<" + node.getName() + ">" + cleaner.getInnerHtml(node) + "</" + node.getName() + ">";
//System.out.println("content " +content);
OutputStream os = response.getOutputStream();
System.out.println("encoding " +response.getCharacterEncoding());
final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
final String html1 = xmlSerializer.getAsString(node);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html1);
renderer.layout();
renderer.createPDF(os);
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void init() throws ServletException {
}
}
Your MIME type is incorrect for PDF. It should be application/pdf.
Change
response.setContentType("text/pdf");
to
response.setContentType("application/pdf");
See https://www.rfc-editor.org/rfc/rfc3778 for the RFC for the PDF MIME type.
Edit: Totally overlooked the "Save as .pdf" question.
You'll also need to add something like:
response.setHeader("content-disposition", "attachment; filename=yourFileName.pdf");
to tell the browser what the default file name should be.

Categories