I am new to JAVA technology,especially Servlets.I need to make a Web application project which have an upload and a download files to/from a server(tomcat).I have already an upload servlet,which works fine.
i have also a download servlet,found on the internet.But the problem is that this servlet allows downloading only a specific file,and the path to this specific file is given in the servlet. I need to let the client see the entire content of my upload folder and select which file he wants to download from this folder.
The code of the download servlet is this:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private static final int BUFSIZE = 4096;
private String filePath;`
public void init() {
// the file data.xls is under web application folder
filePath = getServletContext().getRealPath("") + File.separator;// + "data.xls";
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File file = new File(filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(filePath);
// sets response content type
if (mimetype == null) {
mimetype = "application/octet-stream";
}
response.setContentType(mimetype);
response.setContentLength((int)file.length());
String fileName = (new File(filePath)).getName();
// sets HTTP header
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));
// reads the file's bytes and writes them to the response stream
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
}
The JSP page is this:
<%# 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>Download Servlet Test</title>
</head>
<body>
Click on the link to download: Download Link
</body>
</html>
I searched a lot of servlets but all of them were like this...they allowed downloading only a specific file.
Can anyone help me?
Thank you very much!
Since you're handling the data on the doGet method, you can pass a parameter to the servlet where you indicate the name of the file you want to download. For this, you should assume that the file name exists in your base path. The code could go like this:
HTML
<body>
Click on the link to download:
Download Link
</body>
Java Servlet Code:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//retrieving the parameter by its name
String fileName = request.getParameter("fileName"); //this will return `data.xls`
//using the File(parent, child) constructor for File class
File file = new File(filePath, fileName);
//verify if the file exists
if (file.exists()) {
//move the code to download your file inside here...
} else {
//handle a response to do nothing
}
}
Note that since the code now uses File(String parent, String child) constructor, your filePath should not contain the separator anymore (this will be handled by Java):
public void init() {
// the file data.xls is under web application folder
filePath = getServletContext().getRealPath("");
}
you can do like that
public void doGet(HttpServletRequest req, HttpServletResponse res){
res.setContentType("text/html);
PrintWriter out=response.getWriter();
String fileName="home.txt";
String filePath="d:\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment;fileName=\""+fileName+"\"");
int i;
FileInputStream file=new FileInputStream(filePath +fileName);
while((i=file.read()) !=-1){
out.write(i);
}
file.close();
out.close();
}
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
This more detail and the question how to improve:https://stackoverflow.com/questions/41914092/how-change-servlet-which-download-single-file-but-can-folderfew-files-in-fold
Related
I need to modify the code that read a text file, in a dynamically to read text or html files.
Now the code use only
response.setContentType("text/plain");
because the file is saved in text format. But I would like to save in html format to manage all tag and have a better view, but If I modify in
response.setContentType("text/html");
all file saved as text have a wrong viewer
My code is:
package uk.co.mycode.fax.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uk.co.mycode.fax.dao.mycodeFaxDAO;
import uk.co.mycode.fax.domain.Image;
import uk.co.morpheus.logging.Logger;
public class FaxImageRequest
extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("U");
if (url == null || url.length() < 1) {
url = request.getParameter("URL");
}
Logger.log(4, getClass().getName(), "<**** Entered FaxImageRequest (" + url + ") ****>");
try {
Cookie[] cookies = request.getCookies();
String userId = "";
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("IMPS3IAuserid")) {
userId = cookies[i].getValue();
break;
}
}
}
if (userId.length() < 1) {
userId = "NOT LOGGED ON";
}
mycodeFaxDAO dao = mycodeFaxDAO.getInstance();
Image image = dao.getImage(url);
Logger.log(4, getClass().getName(), "Image: " + image);
if (image != null) {
ServletOutputStream out = response.getOutputStream();
if (image.type.toLowerCase().startsWith("f")) {
response.setContentType("image/tiff");
} else {
//----------------------------------------------------------------------------
response.setContentType("text/plain");
//----------------------------------------------------------------------------
}
for (int i = 0; i < image.bytes.length; ) { out.write(image.bytes, i, (image.bytes.length - i > 4096) ? 4096 : (image.bytes.length - i)); i += 4096; }
dao.updateImageArchive(userId, request.getParameter("U"));
} else {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<HTML>");
pw.println("<BODY>");
pw.println("<B>No image found</B>");
pw.println("</BODY>");
pw.println("</HTML>");
pw.close();
}
} catch (Throwable th) {
Logger.log(1, getClass().getName(), "Error during image read or update:" + th.getMessage());
th.printStackTrace();
}
Logger.log(4, getClass().getName(), "<**** Finished FaxImageRequest ****>");
}
}
I tried to write this:
if (response.getContentType() == null) {
response.setContentType("text/html");
} else {
response.setContentType("text/plain");
}
but it is always null.
Thanks for the support.
The correct answer, if I may bring up your "hosting platform" - is that such settings are usually changed in the hosting platform. I have hosted three different web domains with GCS (Google Cloud Server) because it is (mostly) free.
In Google Cloud, when you save a file, generally it will recognize what type of file you have save (Content-Type) based on the file's extension - '.txt' or '.html'. The Content-Type setting can be changed in Google's bucket file explorer GUI using a mouse. It may also be changed manually at the command line using the GSUTIL command line program.
You may make calls to GSUTIL from Java by using Java's shell execution libraries (the Java Standard library routines for calling UNIX Shell commands). This is what I do...
... But you may even download Google's Java Jar files to access GCS and make Java based calls to GCS for doing things like changing the content type of a storage bucket file....
If you were using.MSFT Azure, or GoDaddy or something else this would be different.
I have very little experience in JAVA (working on my first real program) been looking for a solution for hours. I have hacked together a small program to download PDF files from a link. It works fine for most links but some of them just don't work.
The connection type for all the links that works show up as application/pdf but some links show a connection of text/html for some reason.
I keep trying to rewrite the code using whatever I can find online but I keep getting the same result.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] args) throws Exception {
String link = "https://www.menards.com/main/items/media/UNITE051/SDS/SpectracideVegetationKillerReadyToUse2-228-714-8845-SDS-Feb16.pdf";
String fileName = "File Name.pdf";
URL url1 = new URL(link);
try {
URLConnection urlConn = url1.openConnection();
byte[] buffer = new byte[1024];
double downloaded = 0.00;
int read = 0;
System.out.println(urlConn.getContentType()); // This shows as text/html but it should be PDF
FileOutputStream fos1 = new FileOutputStream(fileName);
BufferedInputStream is1 = new BufferedInputStream(urlConn.getInputStream());
BufferedOutputStream bout = new BufferedOutputStream(fos1, 1024);
try {
while ((read = is1.read(buffer, 0, 1024)) >= 0) {
bout.write(buffer, 0, read);
downloaded += read;
}
bout.close();
fos1.flush();
fos1.close();
is1.close();
} catch (Exception e) {}
} catch (Exception e) {}
}
}
I need to be able to download the PDF from the link in the code.
This is what is saved in a text document of the PDF:
<html>
<head>
<META NAME="robots" CONTENT="noindex,nofollow">
<script src="/_Incapsula_Resource?SWJIYLWA=5074a744e2e3d891814e9a2dace20bd4,719d34d31c8e3a6e6fffd425f7e032f3">
</script>
<body>
</body></html>
The website implemented a check to make sure I was using a browser. I copied the user agent from chrome and it allowed me to download the PDF.
The URL that you are fetching doesn't point to a PDF file. It is pointing to a HTML file which embeds the PDF file. You probably need to closely look at what is the URL to PDF file. You code seems alright.
Just do a cURL on the URL and see. It will most probably return a HTML file.
I'm trying to create an upload-image button and afterward showing the image on a different jsp page.
I want to do this by uploading into the app-root/data/images folder. This works with the below filepath: filePath = System.getenv("OPENSHIFT_DATA_DIR") + "images/";
But how can I show this image on my jsp? I tried using:
<BODY>
<h1>SNOOP PAGE</h1>
Ga weer terug
<% String filepath = System.getenv("OPENSHIFT_DATA_DIR") + "images/";
out.println("<img src='"+filepath+"logo21.jpg'/>");
%>
<img src="app-root/data/images/logo21.jpg"/>
</BODY>
Both these options don't work. I also read that I need to create a symbolic link. But when I'm in my app-root/data or app-root/data/images or in app-root the command ln -s returns missing file operand
The logo21.jpg does show up in my Git bash
#developercorey is right (gave you +1 👍), I just feel the need to explain why:
Your uploaded images ends up in a folder on your server
(String filepath = System.getenv("OPENSHIFT_DATA_DIR") + "images/" is the folder path in the server).
Your rendered HTML "<img src='"+filepath+"logo21.jpg'/> get sent to the client (the user's browser), with the server's filepath url.
Obviously, when the user's browser try to locate the image, using the path of the server, which doesn't exist on the local machine, it won't work.
The best solution, as #developercorey suggested, is to add a new servlet or a filter to serve photos from the OPENSHIFT_DATA_DIR folder:
You'll have a new url mapped to the servlet serving your photo, something like http://your-server/uploaded/
And you can use <img src="http://your-server/uploaded/logo21.jpg" /> in your jsp.
Here's the snippet from How-To: Upload and Serve files using Java Servlets on OpenShift
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.activation.MimetypesFileTypeMap;
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;
#WebServlet(name = "uploads",urlPatterns = {"/uploads/*"})
#MultipartConfig
public class Uploads extends HttpServlet {
private static final long serialVersionUID = 2857847752169838915L;
int BUFFER_LENGTH = 4096;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
for (Part part : request.getParts()) {
InputStream is = request.getPart(part.getName()).getInputStream();
String fileName = getFileName(part);
FileOutputStream os = new FileOutputStream(System.getenv("OPENSHIFT_DATA_DIR") + fileName);
byte[] bytes = new byte[BUFFER_LENGTH];
int read = 0;
while ((read = is.read(bytes, 0, BUFFER_LENGTH)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
is.close();
os.close();
out.println(fileName + " was uploaded to " + System.getenv("OPENSHIFT_DATA_DIR"));
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filePath = request.getRequestURI();
File file = new File(System.getenv("OPENSHIFT_DATA_DIR") + filePath.replace("/uploads/",""));
InputStream input = new FileInputStream(file);
response.setContentLength((int) file.length());
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
OutputStream output = response.getOutputStream();
byte[] bytes = new byte[BUFFER_LENGTH];
int read = 0;
while ((read = input.read(bytes, 0, BUFFER_LENGTH)) != -1) {
output.write(bytes, 0, read);
output.flush();
}
input.close();
output.close();
}
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
}
The best way to serve user uploaded images that you are storing in your OPENSHIFT_DATA_DIR would be to use a servlet as described here: https://forums.openshift.com/how-to-upload-and-serve-files-using-java-servlets-on-openshift?noredirect
This servlet basically takes the path/name of the image that is being requested, reads it from the filesystem and then serves it to the requester.
The OPENSHIFT_DATA_DIR directory is not web-accessible. You can make images stored in the OPENSHIFT_DATA_DIR (aka app-root/data) directory web-accessible by creating a symlink to them from the publicly accessible OPENSHIFT_REPO_DIR.
For one-time use, as a proof of concept:
rhc ssh -a <your_app_name> -n <your_namespace>
ln -sf ${OPENSHIFT_DATA_DIR}images ${OPENSHIFT_REPO_DIR}images
You should now be able to access logo21.jpg at https://<your_app_name>-<your_namespace>.rhcloud.com/images/logo21.jpg, or <img src="/images/logo21.jpg"/>.
The contents of the OPENSHIFT_REPO_DIR are overwritten when you push changes, so you'll want to create the symlink with a deploy hook to re-create it each time you deploy. In .openshift/action_hooks/deploy:
#!/bin/bash
# This deploy hook gets executed after dependencies are resolved and the
# build hook has been run but before the application has been started back
# up again.
# create the images directory if it doesn't exist
if [ ! -d ${OPENSHIFT_DATA_DIR}images ]; then
mkdir ${OPENSHIFT_DATA_DIR}images
fi
# create symlink to uploads directory
ln -sf ${OPENSHIFT_DATA_DIR}images ${OPENSHIFT_REPO_DIR}images
You can upload the file to the DATA DIRECTORY, then copy the file from the DATA DIRECTORY to any folder in the HOME DIRECTORY.
Thereafter you should be able to reference the image as usual in your page but it appears Openshift only displays items from a previous deployment or git push, therefore perhaps it is best to save the file in a database then read it directly from that database.
My project has been created by GAE Plugin for Eclipse (without Maven) and i'm goint to post my code composed by:
home.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload Test</title>
</head>
<body>
<form action="/upload" method="post" name="putFile" id="putFile"
enctype="multipart/form-data">
<input type="file" name="myFile" id="fileName">
<input type="submit" value="Upload">
</form>
</body>
</html>
UploadServlet.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.channels.Channels;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsOutputChannel;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.cloudstorage.RetryParams;
public class UploadServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(UploadServlet.class.getName());
private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());
private String bucketName = "myBucketNameOnGoogleCloudStorage";
/**Used below to determine the size of chucks to read in. Should be > 1kb and < 10MB */
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
#SuppressWarnings("unchecked")
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String sctype = null, sfieldname, sname = null;
ServletFileUpload upload;
FileItemIterator iterator;
FileItemStream item;
InputStream stream = null;
try {
upload = new ServletFileUpload();
res.setContentType("text/plain");
iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
item = iterator.next();
stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
sfieldname = item.getFieldName();
sname = item.getName();
sctype = item.getContentType();
GcsFilename gcsfileName = new GcsFilename(bucketName, sname);
GcsFileOptions options = new GcsFileOptions.Builder()
.acl("public-read").mimeType(sctype).build();
GcsOutputChannel outputChannel =
gcsService.createOrReplace(gcsfileName, options);
copy(stream, Channels.newOutputStream(outputChannel));
res.sendRedirect("/");
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}
}
I tried also to set the maximumSize of the Upload using upload.setMaxSize(-1); or changing the BUFFER_SIZE from 2*1024*1024 into 200*1024*1024, but the issue stil occur. To be more specific, when the uploading reach the 100% I receive this message on the webpage:
Error: Request Entity Too Large Your client issued a request that was too large.
How can i fix that using JAVA and Google Cloud Storage Client Library for Java? (I'm not going to change drastically the Project with other Programming Languages)
Could you please help me to find a solution? Thank you so much!
App Engine request limit is 32Mb. That's why your uploads are failing when you send a file > 32Mb. Checkout Quotas and Limits section.
You have two options for uploading files > 32Mb:
Blobstore API.
You can specify a GCS bucket instead of using Blobstore storage space.
To do that use createUploadUrl(java.lang.String successPath, UploadOptions uploadOptions) method of BlobstoreService.
Here's a sample app: https://github.com/crhym3/java-blobstore-gcs-sample
Signed URLs feature of GCS
Or you could just use Google Drive and store only doc IDs in the datastore :)
I will suggest you to take a look at this great and sample example: http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
A good idea will be to monitor the data stream to the server.
Hope it helps
I have a main form for file uploading. A servlet is doing the upload job. All the files are with the same name structure, so I'm splitting it and getting the parameters. Then I'm placing them into a JSONArray and then I'm passing these parameters to the index page, named test.jsp in my case.
The problem Is, That I have no idea on how to create a table and fill it with the details held in the JSON.
Here my index(test.jsp) page is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<title>File Upload Demo</title>
</head>
<body>
<center>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="uploadFile" multiple/>
<br/><br/>
<input type="submit" value="Upload" />
</form>
${message}
<br />
${jsonString}
</center>
</body>
</html>
I'm using ${jsonString} to check, if the JSON is passed correctly.
It looks like:
[
{
"MDName": "Angel Bankov",
"MDCode": "2288",
"month": "April",
"year": "2013",
"target/achieved": "Target"
},
{
"MDName": "Angel Bankovsky",
"MDCode": "2289",
"month": "April",
"year": "2015",
"target/achieved": "Achieved"
}
]
Here my servlet is:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
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;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* A Java servlet that handles file upload from client.
*
* #author www.codejava.net
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// location to store file uploaded
private static final String UPLOAD_DIRECTORY = "upload";
// upload settings
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
/**
* Upon receiving file upload submission, parses the request to read
* upload data and saves the file on disk.
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
//JSON Declaration
JSONArray splitDetailsArray = new JSONArray();
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
// sets memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// sets temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// sets maximum size of upload file
upload.setFileSizeMax(MAX_FILE_SIZE);
// sets maximum size of request (include file + form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
// this path is relative to application's directory
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
#SuppressWarnings("unchecked")
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();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message",
"Upload has been done successfully!");
}
}
File folder = new File("D:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HDSHubTargetAchieved/upload");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String[] parts = listOfFiles[i].getName().split("[_.']");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
String part5 = parts[4];
// JSON
JSONObject splitDetails = new JSONObject();
splitDetails.put("MDCode", part1);
splitDetails.put("target/achieved", part2);
splitDetails.put("month", part3);
splitDetails.put("year", part4);
splitDetails.put("MDName", part5);
splitDetailsArray.put(splitDetails);
// TEST OUTPUT \\
System.out.println("Code:" + part1 + "\n Target/Achieved: " + part2 + "\n Month: " + part3 + "\n Year: " + part4 + "\n Name: " + part5);
}
}
// TEST OUTPUT \\
System.out.println(splitDetailsArray.toString());
}
} catch (Exception ex) {
request.setAttribute("message",
"There was an error: " + ex.getMessage());
}
// redirects client to message page
request.setAttribute("jsonString", splitDetailsArray.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp");
dispatcher.forward(request, response);
// getServletContext().getRequestDispatcher("/test.jsp").forward(
// request, response);
}
}
The above codes are running on tomcat 6
Again, I'm looking for a way to pass this JSON to a table in the test.jsp file.
In the most cases I'm asking just for an advice, but this time I will need some code examples, because I really have no idea on how to do it. It's my very first touch to the servlets. I lost 2 hours searching for help, but I was unable to find it.
Basically you would to loop through your JSON array using javascript and printing out html table tags. Here is an example answer below that should help you. I just searched for "print html tables from json" on Google.
Convert json data to a html table