Servlet Image Upload - Cannot get other form fields - java

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.

Related

not able to use jquery ajax FormData with servlet

I was trying to make a ajax request to servlet for uploading images using jquery ajax FormData. But I am always getting error response back from servlet. Below is my code:
JSP file
<%# 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="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>File Upload</title>
<script>
function hitThis(){
alert("hello");
var form1 = document.getElementById("form1");
$.ajax( {
url: 'UploadDocs',
type: 'POST',
data: new FormData( form1 ),
processData: false,
contentType: false,
success: function(response) {
alert("success : ");
},
error: function(xhr) {
alert("error : "+JSON.stringify(xhr));
//Do Something to handle error
}
} );
}
</script>
</head>
<body>
<center>
<h1>File Upload</h1>
<form id="form1" class="form-inline" onsubmit="hitThis();">
Amount : <input type="text" value="232" name="amount"/><br>
Select file to upload: <input type="file" name="file" size="60" /><br />
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
Servlet
package org.wpits.ussd;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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 javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.wpits.service.DbService;
import org.wpits.ussd.beans.UserDocs;
/**
* Servlet implementation class UploadDocs
*/
#WebServlet("/UploadDocs")
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class UploadDocs extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbService dbService = new DbService();
private String filePath;
public UploadDocs() {
super();
}
#Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
filePath = getServletContext().getInitParameter("file-upload");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String savePath = filePath;
String amount = request.getParameter("amount");
System.out.println(amount);
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if(fileName!=null && !fileName.equals("")){
InputStream is = part.getInputStream();
File f = new File(savePath+File.separator+fileName);
copyInputStreamToFile(is,f);
}
}
}
private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024*1024*10];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
I am able to write images on described directory path. But the problem is, that I am always getting redirected to ajax's error response. Also, whenever I am restarting the tomcat server and trying to upload files, I am getting "java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly" On second attempt just after the first attempt failed due to error, above written code is able to write files but throwing response to error function of Ajax. Where am I making mistake? It would be very helpful if some one could resolve my problem.
Use this format to fire ajax.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "uploadCsvData",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});
the problem in above code was only that I was using onsubmit() and input type="submit" in my form. That has to be replaced with -- removing onsubmit event and applying onclick event to button instead of input type = "submit". Ajax gets mismatched when combined with basic form.

How to convert absolute path to a relative path so that it can be referenced from an img tag? java web

Creating a web application that lets users upload images.
The code works but having trouble understanding how to get the images in a relative path so that it can be referenced from an img src="" tag?
So far the code takes the multipart request and stores the file in an absolute path on server but this cannot be referenced from an < img > tag..
Any ideas on how to go about this?
UploadFile.java (servlet)
package userServlets;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private boolean isMultipart;
private static final long serialVersionUID = 1L;
public UploadFile() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get session
HttpSession session = request.getSession();
// get the save location for files that user uploads to web app
String appPath = request.getServletContext().getRealPath("/uploads");
// get the name of the currently logged in user
String user = session.getAttribute("loggedInUser").toString();
// create the user's own folder in uploads folder of server.
String directory = appPath + File.separator + user;
File fileSaveDir = new File(directory);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// get the path of the users folder location as a file
File uploads = new File(
request.getSession().getServletContext().getRealPath("/uploads" + File.separator + user));
// Check if request is multipart, if not, sends user back to uplaod page
// (test.jsp)
isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
// Suspicious looking stuff not too sure of but works i guess :/
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(uploads);
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
long sizeInBytes = item.getSize();
String filePath = uploads + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message", "Upload has been done successfully!");
request.setAttribute("filename", fileName);
// *STORE THIS IN DATABASE
request.setAttribute("filepath", filePath);
request.setAttribute("filesize", sizeInBytes);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
request.setAttribute("directory", directory);
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
}
}
test.jsp (upload 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>Insert title here</title>
</head>
<body>
<div class="jumbotron">
<div class="container">
<form method="post" enctype="multipart/form-data" action="UploadFile">
<input type="text" name="description" /> <input type="file"
name="file" /> <input type="submit" />
</form>
</div>
</div>
<h1>"${directory}"</h1>
<h1>"${message}"</h1>
<h1>"${filepath}"</h1>
<h1>"${filename}"</h1>
<h1>"${filetype}"</h1>
<h1>"${filesize}"</h1>
<img src="${filepath}">
<hr />
<div class="jumbotron">
<img alt="" src="hmmmmmm">
</div>
</body>
</html>
Figured it out after reading this link
If you have full control over the images folder, then just drop the
folder with all images, e.g. /images directly in servletcontainer's
deploy folder, such as the /webapps folder in case of Tomcat and
/domains/domain1/applications folder in case of GlassFish. No further
configuration is necessary.
literally drag and drop the file into the web application folder in your ide.
then you do this

Can't get a Parameter in Servlet [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
I want to upload multiple files to server and get a parameter "testname" in a JSP page . But it always return a null value.
I found the cause of error. Because of "enctype="multipart/form-data"". If I remove it from the form, I can get a parameter but I can't upload multiple files to server. How can I do both of them?
lib: http://www.java2s.com/Code/Jar/c/Downloadcosmultipartjar.htm
index.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>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input name="testname" type="text">
<input type="file" id="file" name="file1" accept="image/*" multiple="muliple" required/><br>
<input type="submit"/>
<br><br> ${requestScope.message}
</form>
</body>
</html>
UploadServlet.java
package MyPackage;
import java.io.IOException;
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 javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
/**
* Servlet implementation class UploadServlet
*/
#WebServlet("/UploadServlet")
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 {
String testname=request.getParameter("testname");
System.out.print(testname);
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
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
} catch (java.io.IOException ioe) {
resp = ioe.getMessage();
}
request.setAttribute("message", resp);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
While using enctype="multipart/form-data", you will not get your parameters by calling request.getParameter(). The parameters are a part of the stream now.
I suggest you check the question How to upload files to server using JSP/Servlet?

Jsp doesn't show swf File

I have a Webproject with JavaEE (Tomcat, Jsp, Servlets)
I want to Show a SWF in my Jsp Page (game.jsp). For doing this i Need a Servlet, which is this:
package src;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
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 util.SystemEnviroement;
/**
* Servlet implementation class ImageServlet
*/
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
String imageName = request.getParameter("imageName");
SystemEnviroement env = new SystemEnviroement();
String filename = env.gameFolder + "/" + imageName;
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
// sc.log("Could not get MIME type of " + filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
// Set content size
File file = new File(filename);
response.setContentLength((int) file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
}
My game.jsp is this:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# page import="util.*"%>
<%# page import="constants.*"%>
<%# page import="java.io.IOException"%>
<!DOCTYPE html>
<html >
<head>
<jsp:include page='header.jsp'/>
<%
String gamename = (String) request.getAttribute("javax.servlet.forward.request_uri");
int index_name = gamename.lastIndexOf("/");
gamename = gamename.substring(index_name+1,gamename.length());
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="background-color:#630592;
background-repeat:no-repeat;"
>
<div class="body">
<%
try {
//SystemEnviroment wird im Konstruktor gesetzt
SystemEnviroement en = new SystemEnviroement();
String datei = en.imageViewPath + gamename +".swf";
%>
<div class=gameswf>
<a> <embed src='<%=datei %>' > </embed> </a>
</div>
<%
}catch(IOException e){
e.printStackTrace();
}
%>
</div>
</body>
</html>
So i have debugged my Project, all thinks Looks well. But after calling the Servlet, the game.jsp doesn't Show the SWF File.
The htmltext(sourcecode) also Looks well, but the game.jsp doesn't Show the SWF File:
<div class=gameswf>
<a> <embed src='http://localhost:8080/Game/imageView?imageName=3-pandas.swf'> </embed> </a>
</div>
If i call this URL in my running web Project "http://localhost:8080/Game/imageView?imageName=3-pandas.swf", i can sell the SWF File and all is fine.
Do you have any idea why the jsp page doesn't Show my SWF File. If i go to the Internet explorer add ons, i can also see that Shockwave Flash Object is loading.
Thanks for helping !
This is the Image from ie 11 network monitoring feature from developer Tools:
I suggest you to create an html file (with html extension) and write the code you expect from the jsp to generate.
Once you make the swf work in html file, it will be a piece of cake to develop the proper jsp code in order to generate that html file.

How to use excel to pdf REST api provided by ConvertApi?

I am planning to use, excel to pdf api (REST) in my java code provided by ConvertApi.
please share the code snippet to be used for the same.
Thanks in advance.
Please try the code below
Library
package com.excel2pdfconvert.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class Xls2PDFConvertBean {
private File file;
private String outputDir;
private String filesize;
private String filename;
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public void setExcelFile(File file) {
this.file = file;
}
public String getFilesize() {
return filesize;
}
public String getFilename() {
return filename;
}
/**
* Run request for page conversion
* #return resultcode "0" in error, "1" in success
* #throws UnsupportedEncodingException
*/
public String doRequest() throws UnsupportedEncodingException{
String resultcode = "0";
HttpPost httppost = new HttpPost("https://v2.convertapi.com/convert/xlsx/to/pdf");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
entity.addPart("file", new FileBody(file, "binary/octet-stream"));
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+File.separator+filename);
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultcode;
}
}
The web page
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# page import="com.excel2pdfconvert.example.Xls2PDFConvertBean" %>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%# page import="java.util.*" %>
<%# page import="java.io.File" %>
<%# page import="org.apache.commons.fileupload.FileItem" %>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Excel2Pdf Api Demo
</title>
<script type="text/javascript">
function BeforeConvert() {
document.getElementById('LabelMessage').innerHTML = 'Please wait...';
document.getElementById('HyperLinkFile').innerHTML = '';
document.getElementById('LabelFileSize').innerHTML = '';
document.getElementById('LabelFileName').innerHTML = '';
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div>
<h1>Excel2Pdf Api Demo</h1>
Upload Excel file:
<input type="file" name="excel" />
<input type="submit" name="btnConvert" value="Convert" onclick="BeforeConvert();" id="btnConvert" />
<br />
<br />
<% if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
File uploadedFile = null;
String[] allowedExt = {"csv", "xls", "xlsx", "xlsb", "xlt", "xltx"};
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (! item.isFormField()) {
//Check for valid excel extensions
String fileName = item.getName();
boolean isValid = false;
for(String ext : allowedExt){
if(fileName.contains(ext)){
isValid = true;
break;
}
}
if(isValid){
uploadedFile = new File(application.getRealPath("/") + "/" + fileName);
item.write(uploadedFile);
}
}
}
if(uploadedFile == null){
out.println("<div>Please upload file in following format: csv, xls, xlsx, xlsb, xlt, xltx");
}else{
Xls2PDFConvertBean xls2pdf = new Xls2PDFConvertBean();
xls2pdf.setOutputDir(application.getRealPath("/"));
xls2pdf.setExcelFile(uploadedFile);
String resultcode = xls2pdf.doRequest();
//Remove uploaded file after conversion
uploadedFile.delete();
if(resultcode == null || "False".equals(resultcode)){
out.println("<div>Can not convert file</div>");
}else{
%>
<span id="LabelMessage">Conversion successful </span>
<br />
<a id="HyperLinkFile" href="<%= xls2pdf.getFilename() %>" >Click here to open file </a>
<br />
<span id="LabelFileSize">File size: <%= xls2pdf.getFilesize() %></span>
<br />
<span id="LabelFileName">File name: <%= xls2pdf.getFilename() %></span>
<%
}
}
}else{
%>
<span id="LabelMessage"></span>
<%
}
%>
</div>
</form>
</body>
</html>

Categories