uploading files using jsp and servlet - java

I am developing a web application using Java. From my index page I need to upload a file with some other fields such as some texts and numbers using input tags.
this is my jsp file.
<select name="category">
<option value="">-Select-</option>
<option value="Mobile Phones">Mobile Phones</option>
<option value="Automobile">Automobile</option>
<option value="Computers">Computers</option>
</select><br/><br/>
<label>Title: </label><input type="text" name="Title"/><br/><br/>
<label>Photo: </label><input type="file" name="photo"/><br/><br/>
<label>Description: </label><input type="text" name="description"/><br/><br/>
<label>Price: </label><input type="text" name="price"/><br/><br/>
<input type="submit" value="Post">
I found some articles which use Apache commons, but in all of that, I can get only the image. All the other values get set to null. The article I followed is this.
I need to know how to get other values as well. (In this case category, title, photo etc.)
How can I do that?
Thank you!
EDIT:
This is my servlet.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.im.dao.PostAdDao;
import com.im.dao.PostAdDaoImpl;
import com.im.entities.Advertiesment;
#WebServlet("/postAd")
#MultipartConfig
public class PostAdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "C:/uploadss";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Advertiesment ad = new Advertiesment();
PostAdDao pad = new PostAdDaoImpl();
PrintWriter out = response.getWriter();
String name = null;
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(item.isFormField()){
String cat = request.getParameter("category");
System.out.println("INFO: Category : "+cat);
if( cat != null ){
ad.setCategory(cat);
}
String title = request.getParameter("adTitle");
if( title != null ){
ad.setTitle(title);
System.out.println("INFO: Title : "+title);
}
String des = request.getParameter("description");
if(des != null){
ad.setDescription(des);
System.out.println("INFO: Description : "+des);
}
try{
Double price = Double.parseDouble(request.getParameter("price"));
if(price != null){
ad.setPrice(price);
System.out.println("INFO: Price : "+price);
}
}catch(Exception e){
System.out.println("ERROR: Occured while setting price in servlet");
}
}else{
name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
request.setAttribute("message", "Advertiesment Posted Successfully");
System.out.println("INFO: Advertiesment Posted Successfully");
System.out.println("INFO: File name : "+name);
ad.setPhoto(name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
System.out.println("\nERROR: Occured while posting the advertiesment! "+ex );
}
}else{
//request.setAttribute("message","Sorry this Servlet only handles file upload request");
}
//request.getRequestDispatcher("/result.jsp").forward(request, response);
String msg = pad.postAd(ad);
}
}

I found some articles which use Apache commons, but in all of that, I
can get only the image
No . you can get other items also from the request .
DiskFileUpload upload = new DiskFileUpload();
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
//get form fields here
}
else {
//process file upload here
}}
Read the documentation here to understand more on this and also a nice thread here values of input text fields in a html multipart form
Update:
String cat = item.getFieldName("category") instead of request.getParameter("category");
Because you are parsing the request object . so you need to get it from FileItem object . similarly for other fields too.

Related

how to create a PDF using a java servlet in itext 7

I am making a web app that allows you to buy a ticket online. I used a java class called CreatePDF.java to make the PDF(which is what the ticket will be) it works offline but when i try and use it through a servlet the pdf is broken. I have tried to look everywhere that solves this problem using itext7 but no one has
OrderServlet.java
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class OrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
// HsqlShopDB db = new HsqlShopDB();
String name = request.getParameter("fname");
String mobile = request.getParameter("number");
String email = request.getParameter("email");
String cemail = request.getParameter("cemail");
HsqlShopDB db = new HsqlShopDB();
Event e = db.getEvent("1");
Ticket t = db.getTicket("1");
createPDF c = new createPDF();
try{
c.CreatePDF("10293838458493",89,t,e,name);
}catch (Exception ex) {
System.out.println(ex);
}
if (name!=null){
// db.order(basket, name, email,mobile);
// email e = new email();
// e.orderEmail(basket,name,email,mobile);
// basket.clearBasket();
}else{
System.out.println("name is not here");
}
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Thank you" + name + "for ordering a "+ e +"ticket</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
CreatePDF.java
import java.io.*;
import com.itextpdf.io.image.*;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.font.constants.FontWeights;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.Text;
public class createPDF{
public void CreatePDF(String orderID, Integer random, Ticket t, Event e,String customer) throws Exception {
// Creating a PdfWriter
String code = Integer.toString(random);
String dest = "../webapps/EMT/WEB-INF/classes/EMTShop/PDFs/" + code + ".pdf";
PdfWriter writer = new PdfWriter(dest);
String barcodePath= code + ".png";
GenerateQRCode g= new GenerateQRCode();
g.generateQRcode(code);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a PdfCanvas object
// Creating a new page
PdfPage pdfPage = pdf.addNewPage();
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Setting color to the rectangle
Color color = ColorConstants.BLACK;
canvas.setColor(color, true);
// creating a rectangle
canvas.rectangle(10, 10,600,200 );
// Creating Paragraphs
Text para1 = new Text("EMT Entertainment Presents: "+ e.title +"!");
Text para2 = new Text( t.type + " £"+ t.price + "\n Ordered By: " + customer +" \n Enter Before " + t.entry);
Text para3 = new Text(e.location +", " + e.postcode +"\n "+ e.date + " \n Order ID: "+ orderID);
Text para4 = new Text("Permits 1 x Person(s)");
// Setting font of the text
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
PdfFont font2 = PdfFontFactory.createFont(StandardFonts.HELVETICA);
para1.setFont(font);
para1.setFontSize(17);
para2.setFont(font);
para2.setFontSize(15);
para3.setFont(font2);
para4.setFont(font2);
Paragraph paragraph1 = new Paragraph(para1);
Paragraph paragraph2 = new Paragraph(para2);
Paragraph paragraph3 = new Paragraph(para3);
Paragraph paragraph4 = new Paragraph(para4);
// Setting the position of the paragraph to the page
paragraph1.setMarginLeft(10);
paragraph1.setMarginTop(160);
paragraph2.setMarginLeft(10);
paragraph2.setMarginTop(30);
paragraph3.setMarginLeft(20);
paragraph3.setMarginTop(50);
paragraph4.setMarginLeft(20);
paragraph4.setMarginTop(60);
// Creating an ImageData object
String imFile = "EMTShop/images/EMTLogo.jpeg";
String imFile2 = "EMTShop/images/"+ e.title + ".jpg";
String imFile3 = "EMTShop/barcodes/" + barcodePath;
ImageData data = ImageDataFactory.create(imFile);
ImageData data2 = ImageDataFactory.create(imFile2);
ImageData data3 = ImageDataFactory.create(imFile3);
// Creating an Image object
Image image = new Image(data);
Image image2 = new Image(data2);
Image image3 = new Image(data3);
// Setting the position of the image to the center of the page
image.setFixedPosition(250, 700);
image.setHeight(100);
image.setWidth(100);
image2.setFixedPosition(425, 500);
image2.setHeight(150);
image2.setWidth(100);
// Creating Barcode
image3.setFixedPosition(400, 300);
image3.setHeight(150);
image3.setWidth(150);
// Adding paragraphs to document
document.add(paragraph1);
document.add(paragraph2);
document.add(paragraph3);
document.add(paragraph4);
// Adding image to the document
document.add(image);
document.add(image2);
document.add(image3);
// Closing the document
document.close();
System.out.println("Image added");
}
public static void main(String args[]) throws Exception{
createPDF c = new createPDF();
HsqlShopDB db = new HsqlShopDB();
Event e = db.getEvent("1");
Ticket t = db.getTicketsEvent(e.eventid);
c.CreatePDF("10293838458493",1999,t,e,"tope oshin");
}
}
Details.jsp uses a form to send information to the servlet
<div class= "blog">
<div class= "form">
<h1>Please confirm your details</h1>
<form method="POST" action="OrderServlet">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
<label for="number">Phone Number:</label>
<input type="text" id="number" name="number">
<label for="email">E-Mail Address:</label>
<input type="text" id="email" name="email">
<label for="cemail">Confirm E-Mail Address:</label>
<input type="text" id="cemail" name="cemail">
<input type="submit" value="proceed to checkout" name="VIP1">
</form>
</div>
</div>

Maintain Conversation After Exception (Handled in Pages.xml)

I'm working in a project that I didn't originally start, so there are a lot of artifacts and conventions that I cannot change without considerable effort. Anyway, here's the problem. I need to do multiple file uploads (that are "children" to the entity that is being edited on the "main" parent page) that get cached on the server so that they can be sent somewhere else if/when the user submits. The files uploaded also include metadata that the user enters. The best way I have figured to do this is to render a "dialog" that has an iframe that does the uploading and has the input for the metadata. Then I created an override (using install precedence) of Seam's multipart filter that uses the Apache file upload jar and a custom request wrapper that carries my information into the action call on the server. All goes well unless I throw an exception out of the filter, for example, if the request size is too big. The exception is caught and handled by a pages.xml declaration.
<exception class="org.jboss.seam.web.FileUploadException">
<redirect view-id="#{facesContext.externalContext.requestServletPath}">
<message severity='ERROR'>#{org.jboss.seam.handledException.message}</message>
</redirect>
</exception>
When I normally submit the form in my dialog frame, the conversation in the frame remains (as I want), when the exception is caught, I get a new one (as I don't want). I want the error messages passed by the exception shown in the global messages area of the frame, but I need to remain in the same conversation as before since the "children" that are being added in the dialog are children to the "parent" entity in the main page. Here is the form inside the frame code. I have tried s:button (does not submit the form), tried parameters, and tried hidden inputs with the conversation id.
<h:form id="attachmentModalForm" enctype="multipart/form-data" autocomplete="off" style="background-color: #FFFFFF;">
<ui:include src="layout/messages.xhtml" />
<div id="attachmentModalMain" class="modalMain">
<s:decorate id="attachmentDescriptionDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.description']}<s:span styleClass="required">*</s:span></ui:define>
<h:inputText id="attachmentDescription" value="#{attachmentAction.description}" styleClass="textbox" />
</s:decorate>
<s:decorate id="attachmentFileDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.file']}<s:span styleClass="required">*</s:span></ui:define>
<input id="attachmentFile" name="attachmentFile" type="file" />
</s:decorate>
</div>
<div id="attachmentModalSubmit" class="modalSubmit">
<h:commandButton id="attachmentSubmitButton" value="#{messages['action.text.submit']}" action="#{attachmentAction.addAttachment()}" onclick="attachmentSubmit();" />
<button id="attachmentCancelButton" type="button" value="#{messages['action.text.cancel']}" onclick="window.parent.hideAttachmentModal();">#{messages['action.text.cancel']}</button>
</div>
<input type="hidden" name="cid" value="#{conversation.id}" />
</h:form>
Here is the filter that overrides Seam's multipart filter.
package XXXXXXXXXXXXX.attachment;
import java.io.File;
import java.io.IOException;
import java.rmi.server.UID;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.annotations.web.Filter;
import org.jboss.seam.web.AbstractFilter;
/**
* This filter is used to override Seam's multipart filter so that we
* can have multiple temporary files on the server cued and ready to
* go to XXXXXXXXX. It uses the Apache Commons FileUpload objects to
* handle the parsing of the request and the temporary files.
*
*/
#Scope(ScopeType.APPLICATION)
#Name("org.jboss.seam.web.multipartFilter")
#Install(precedence = Install.APPLICATION)
#BypassInterceptors
#Filter(within={"org.jboss.seam.web.ajax4jsfFilter", "org.jboss.seam.web.exceptionFilter"})
public class MEDWareMultipartFilter extends AbstractFilter {
// This is unused, we always want temp files since we are caching before upload to XXXXXXXXX.
// Leaving it in to mirror Seam's multipart filter, in case it gets set from the components.xml.
#SuppressWarnings("unused") private boolean createTempFiles = true;
private int maxRequestSize = -1;
private String acceptedFileExtensions = "txt,pdf,doc,docx,xls,xlsx";
public void setCreateTempFiles(boolean createTempFiles) { }
public void setMaxRequestSize(int maxFileSize) {
this.maxRequestSize = maxFileSize;
}
public String getAcceptedFileExtensions() {
return acceptedFileExtensions;
}
public void setAcceptedFileExtensions(String acceptedFileExtensions) {
this.acceptedFileExtensions = acceptedFileExtensions;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(response instanceof HttpServletResponse)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (ServletFileUpload.isMultipartContent(httpRequest)) {
File repository = (File) this.getServletContext().getAttribute("javax.servlet.context.tempdir");
DiskFileItemFactory factory = new DiskFileItemFactory(0, repository);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxRequestSize);
List<FileItem> formItems = null;
try {
formItems = upload.parseRequest(httpRequest);
} catch (SizeLimitExceededException slee) {
throw new org.jboss.seam.web.FileUploadException("File size excededs maximum allowed.", slee);
} catch (FileUploadException fue) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file.", fue);
}
Map<String, String> parameters = new HashMap<String, String>();
Map<String, File> fileParameters = new HashMap<String, File>();
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (item.isFormField()) {
parameters.put(item.getFieldName(), item.getString());
} else {
String fileName = item.getName();
// This is for IE7 (and Safari?) which sends the whole path.
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
if (!MyMultipartRequestUtils.isValidFileType(acceptedFileExtensions, fileName)) {
throw new org.jboss.seam.web.FileUploadException("The file type is not an accepted file type.");
}
File tempFile = null;
try {
tempFile = File.createTempFile(new UID().toString().replace(":", "-"), ".upload");
tempFile.deleteOnExit();
item.write(tempFile);
} catch (Exception e) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file. Could not write file to server.");
}
fileParameters.put(fileName, tempFile);
}
}
}
MyMultipartRequestWrapper requestWrapper = new MyMultipartRequestWrapper(httpRequest, parameters, fileParameters);
chain.doFilter(requestWrapper, response);
} else {
chain.doFilter(request, response);
}
}
}
So, to reiterate, if I use the frame to upload files, everything works and the frame continues on the same conversation adding each child to the parent, if I upload a file that is too big, I get the correct message in the global message area of the frame, but the conversation get incremented and then the children are obviously being added to a new parent entity in the new conversation. Any help would be greatly appreciated.
I just ended up adding a field to my custom request wrapper to carry any exceptions I wanted to handle and then handled them in the
#{attachmentAction.addAttachment()}
action call further up the request chain. All works now, I just add my faces messages from there and the conversation does not get incremented the same as if I had a successful upload.

Dispaly image through servlet on jsp

From the Servlet I am generating JPEG image and writing in the outputstream of that servlet.By jsp i am calling this Servlet URL and displaying the image as similar to user profile with photo.
Here the problem is,When first time login it will generate the image dynamically and display but next time if I login with out closing the browser first it will display the privies picture and then it will display the current picture.
JSP:
<div class="sortable">
<div class="box span5" style="margin-left: 50px;">
<div class="box-header well">
<h2><i class="icon-th"></i>Employee Attendance</h2>
<div class="box-icon">
<i class="icon-chevron-up"></i>
</div>
</div>
<div class="box-content" style="height:230px;" >
<img border="0" src="admissionenquirylist.do?method=image" alt="Pulpit rock" width="370" height="240"/>
</div>
</div>
</div>
Servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.admission.process;
import com.google.gson.Gson;
import com.treamis.entity.Academicyearmaster;
import com.treamis.entity.AdmissionenquiryStudentdetails;
import com.treamis.entity.EmployeeEntity;
import com.treamis.hr.employee.PaginationClass;
import com.treamis.hr.employee.SetPaginationRecords;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.ServletOutputStream;
/**
*
* #author ranjeeth.g
*/
public class AdmissionEnquiry extends LookupDispatchAction {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
/**
* Provides the mapping from resource key to method name.
*
* #return Resource key / method name map.
*/
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("button.admissionEnqiryList", "admissionEnqiryList");
map.put("button.image", "image");
map.put("button.delete", "delete");
return map;
}
/**
* Action called on Add button click
*/
public void admissionEnqiryList(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
// TODO: implement add method
try {
String stdutendserch = request.getParameter("admissionenquirysearch");
System.out.println("stdutendserch = " + stdutendserch);
Admissionservices as = new Admissionservices();
List<Enquirylistbean> stdserc = as.getStudentEnquirySerch(stdutendserch);
if (stdserc != null) {
response.setContentType("application/json");
String json = new Gson().toJson(stdserc);
System.out.println("json = " + json);
response.getWriter().print(json);
} else {
response.setContentType("application/json");
String json = new Gson().toJson(null);
response.getWriter().print(json);
}
} catch (Exception e) {
e.printStackTrace();
}
// return mapping.findForward(SUCCESS);
// return null;
}
/**
* Action called on Edit button click
*/
public void image(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
try {
System.out.println("Inside the image responce action");
response.setContentType("image/jpeg");
Academicyearmaster academicyearmaster = (Academicyearmaster) request.getSession().getAttribute("academicyear");
// String ss = getServlet().getServletContext().getRealPath("\\");
// String filePath = ss + "img\\paichart.png";
ServletOutputStream out = response.getOutputStream();
// System.out.println("out = " + out);
// String filePath2 = ss + "img\\paichart1.png";
// ExecutorService executor = Executors.newFixedThreadPool(2);
com.treamis.hr.employee.Sendded sendded = new com.treamis.hr.employee.Sendded(out, academicyearmaster);
sendded.image();
// executor.execute(sendded);
} catch (Exception e) {
e.printStackTrace();
}
// TODO: implement edit method
// return mapping.findForward(SUCCESS);
}
/**
* Action called on Delete button click
*/
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws java.lang.Exception {
// TODO:implement delete method
return mapping.findForward(SUCCESS);
}
/* And your JSP would have the following format for submit buttons:
<html:form action="/test">
<html:submit property="method">
<bean:message key="button.add"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.edit"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.delete"/>
</html:submit>
</html:form>
*/
}
Java code to generate image:
try{
ChartUtilities.writeChartAsJPEG(out, chart, 600, 400, info);
// System.out.println("file2 = " + file1);
} catch (Exception e) {
e.printStackTrace();
return "success";
} finally {
out.close();
}
The answer lies in the Life cycle of Servlet. Even though multiple request comes to a servlet only one instance of the Servlet class will be created.
Check if you have any resources that is global and fix it.
Or post full servlet class for better response.
Hope it helps!
I think if you use differents files names to each file save in disk you will not have this problem again.

Upload file from HTML form through Servlet to Google Cloud Storage (using Google Cloud Storage Client Library for Java)

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

Populate a grid/table with json data

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

Categories