Need help on File uploading in JSF
Hi All,
i have to upload some document into IBM DB2 Content Management using JSF Portlet.
Is it possible to upload a document( in my case it is an image) using JSF Portlet into IBM DB2 Content Management? and also i need to keep the reference of the uploaded document in DB2 database.
i need some sample code to do this.
the tools i am using are
RAD 6.0 as IDE
IBM DB2 Content Managener 8.3
IBM DB2 8.2
its an urgent requirement please help me out in this regard
If it's possible in Portlets i don't know, but in JSF is possible with the Tomahawk component to upload files.
See
www.myfaces.org
Try it.
Similar Messages
-
Need help for file upload - reposted for Steve Muench
Hi Steve,
I have been involved developing a web application that requires a file upload operation. I have studied your example on Upload Text File and Image Example in the Not Yet Documented ADF Sample Applications section. I got the file upload part worked but could not get the original file name to populate the name field..i.e. if I upload myFile.txt to the database, the name field will be myFile.txt (not the name enter by user). Is there a way to capture the filename info? or is it possible to do so within ADF framework? I am using ADF/Struts/JSP with ORDDoc data type. Thanks very much.
BillHello Nani,
You need to change any settings in 'FILE' transaction. This transaction is used to set up Logical file paths. ( In general it will be set already for your system).
You can use the following code.
DATA: LC_LOGICAL_FILENAME_EXPSRC LIKE RCGIEDIAL-IEFILE
VALUE 'EHS_IMP_SOURCES'.
DATA: L_EMERGENCY_FLAG TYPE C.
DATA: L_FILE_FORMAT LIKE FILENAME-FILEFORMAT.
data : X_RCGIEDIAL LIKE RCGIEDIAL occurs 0 with HEADER LINE.
read the default pathname on application server
CALL FUNCTION 'FILE_GET_NAME'
EXPORTING
CLIENT = SY-MANDT
LOGICAL_FILENAME = LC_LOGICAL_FILENAME_EXPSRC
OPERATING_SYSTEM = SY-OPSYS
parameter_1 = ' '
PARAMETER_2 = ' '
USE_PRESENTATION_SERVER = ' '
WITH_FILE_EXTENSION = ' '
USE_BUFFER = ' '
IMPORTING
EMERGENCY_FLAG = L_EMERGENCY_FLAG
FILE_FORMAT = L_FILE_FORMAT
FILE_NAME = X_RCGIEDIAL-IEFILE
EXCEPTIONS
FILE_NOT_FOUND = 1
OTHERS = 2.
write :/ 'file format', L_FILE_FORMAT,
/ 'file name', X_RCGIEDIAL-IEFILE.
Thanks,
Jyothi -
Need help w/ file uploading!
hi! i'm writing a JSP where the client has the possibility to upload image-files
to the server.. anyone have a good way to it? and if so how?
if you are referring me to some java-classes i would like to get proper
information on how to append them in the best way possible...
i've heard about the MaybeUpload package by Weft but there's one thing i
don't understand... in the form you use the <input file=""> tag, but how do i
obtain the file? if use request.getParameter() i would get the path, wouldn't i??
hope you can help me out!read this.
http://www.onjava.com/pub/a/onjava/2001/04/05/upload.html?page=1 -
I am setting up a new iMac and need help syncing files to Dropbox. On my old computer I had it set where when I saved a document, it was saved on my hard drive, as well as to a folder in Dropbox. I can't remember how I set this up. Any help?
The way that Dropbox works is that it keeps a copy of all your files in your local Dropbox folder on your hard drive (which is, by default, directly under your home folder). Adding files to that folder will sync them to the Dropbox server.
You do of course have to download the Dropbox application to enable this (download link at the top right of http://dropbox.com ).
Matt -
File Upload problem: JSF, IBM WPS and Portlet - Please HELP Vey Very Urgent
I want to upload a file from the front end using JSF and Portlets deployed on IBM WebSphere Portal.
I have used Apache's commons file upload functionality as the file upload provided in JSF doesnot work with portlets and the action event is not invoked If I keep enctype="multipart/form-data". So I included 3 forms in my Faces JSP file.
1) h:form = For displyign error message on screen
2) html:form = Include the enctype="multipart/form-data" and the input type file for uploading. And a submit button
3) h:form: Here I have a command link which is remotely excuted on click of sumit button in my html form. This is to invoke the action event in the pagecode to get the bean value from the context.
Now in the my doView method in the portlet, isMultipartContent(httpservletrequest) always returns null as the content type is text/html and not multipart. Onclick of the submit button in the the html form I am calling a javascript function which sets the __LINK_TARGET__ to the command link in the 3rd h:form which will call the page code.
The problem here is action is invoked only when I return false from the above javascript else it will trigger for the first time and from second time onwards it will not invoke the action event in the pagecode method. Whent the javascript function returns false, the content type is always text/html. However if I return "true" from the javascript the content type is multipart/form-data, but the action is not triggered for the second time. So basically when the javascript functions returns true, for the first click everything works perfectly. When it returns false, the content type is text/html, but the action is invoked in the page code every time.
Returning always true would solve my problem with the content type, but the action with the command link will not get invoked always as its some type of problem with h:commanLink :(.
I guess I gave too much info. Heres my code stepby step.
Can somebody please tell me , how I should also invoke the action in the page code and get the content type as "multipart/form-data" at the same time.
1:
======================= Faces JSP File: BPSMacro.jsp ====================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="IBM Software Development Platform">
<meta http-equiv="Content-Style-Type" content="text/css">
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://www.ibm.com/jsf/html_extended" prefix="hx"%>
<%@taglib uri="/WEB-INF/tld/j4j.tld" prefix="j4j"%>
<%@taglib uri="/WEB-INF/tld/core.tld" prefix="core"%>
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="false"%>
<portlet:defineObjects />
<link rel="stylesheet" type="text/css"
href='<%= renderResponse.encodeURL(renderRequest.getContextPath() + "/theme/stylesheet.css") %>'
title="Style">
<script type="text/javascript">
function formSubmit() {
var formName2 = document.getElementById("proxy_form_main_").title;
var formName1 = document.getElementById("BPSMacroFormId").title;
document.getElementById("__LINK_TARGET__").value = document.getElementById("proxy_HD_COMMAND_").title;
document.getElementById(formName2).submit();
return false;
</script>
<f:view>
<hx:scriptCollector id="bpsMacroScriptCollector">
<f:loadBundle var="bps" basename="bordereauprocessingsystem" />
<table bgcolor="#FFF9C3">
<tr>
<td><h:form id="BPSMacroFormMain" styleClass="form">
<table class="tablemiddle" cellspacing="0" cellpadding="0">
<tr>
<td><h:messages layout="table" styleClass="errormessage"
id="ValidationErrorMsg" /> </td>
</tr>
</table>
<j4j:idProxy id="proxy_form_main_0_" />
</h:form></td>
</tr>
<tr>
<td>
<form id="BPSMacroFormId" enctype="multipart/form-data">
<table bgcolor="#FFF9C3">
<tr>
<td height="36" width="324">Worksheet <input type="file"
name="upfile" /></td>
</tr>
<tr>
<td align="center" width="324"><input TYPE="submit"
onclick="return formSubmit();" value="Upload">
</td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<h:form id="BPSMacroFormMain2" styleClass="form">
<table cellspacing="2" cellpadding="2" class="tablemiddle">
<tbody>
<tr>
<td colspan="2" align="center"><h:commandLink
styleClass="commandLink" id="lnkuserdelete"
action="#{pc_BPSMacro.doIdUpload1Action}">
<hx:graphicImageEx
styleClass="graphicImageEx" id="imgBtnCreateUser"
value="/theme/images/btnUpload.gif" style="border:0;cursor:pointer"></hx:graphicImageEx>
<j4j:idProxy id="proxy_HD_COMMAND_" />
</h:commandLink></td>
<h:inputHidden id="dtSize"
value="#{pc_BPSMacro.fileDetailsList.clicked}">
<j4j:idProxy id="proxy_clicked_" />
</h:inputHidden>
</tr>
</tbody>
</table>
<j4j:idProxy id="proxy_form_main_" />
</h:form>
</td>
</tr>
</table>
</hx:scriptCollector>
</f:view>
================== END: FACES JSP FILE: BPSMacro.jsp ========================
2:
=================== Action event in the Page Code: BPSMacro.java ============
public String doIdUpload1Action() {
System.out.println("PageCode");
FacesContext context = FacesContext.getCurrentInstance();
BPSMacroDetailsDataBean fileDetails = (BPSMacroDetailsDataBean)context.getApplication().createValueBinding("#{fileDetails}").getValue(context);
BPSMacroListDataBean fileDetailsList = (BPSMacroListDataBean)context.getApplication().createValueBinding("#{fileDetailsList}").getValue(context);
PortletSession sess = (PortletSession)context.getExternalContext().getSession(false);
sess.setAttribute("BPS_MACRO_CONTEXT", context, PortletSession.APPLICATION_SCOPE);
sess.setAttribute("BPS_MACRO_FILE_DETAILS", fileDetails, PortletSession.APPLICATION_SCOPE);
sess.setAttribute("BPS_MACRO_FILE_LIST", fileDetailsList, PortletSession.APPLICATION_SCOPE);
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
request.getContentType();
return "gotoBPSMacro";
============== END Of Page Code Action event ==============================
3:
============== doView() Portlet method ================================
public void doView(RenderRequest arg0, RenderResponse arg1)
throws PortletException, IOException {
String METHOD_NAME = "doView(RenderRequest arg0, RenderResponse arg1)";
Logger.debug(this.getClass(), METHOD_NAME, "Entering BPSMacroPortlet");
FacesContext context = FacesContext.getCurrentInstance();
PortletSession sess1 = arg0.getPortletSession(true);
BPSMacroDetailsDataBean fileDetails = new BPSMacroDetailsDataBean();
BPSMacroListDataBean fileDetailsList = new BPSMacroListDataBean();
context = (FacesContext)sess1.getAttribute("BPS_MACRO_CONTEXT", PortletSession.APPLICATION_SCOPE);
if(context != null){
fileDetails = (BPSMacroDetailsDataBean)sess1.getAttribute("BPS_MACRO_FILE_DETAILS", PortletSession.APPLICATION_SCOPE);
fileDetailsList = (BPSMacroListDataBean)sess1.getAttribute("BPS_MACRO_FILE_LIST", PortletSession.APPLICATION_SCOPE);
sess1.removeAttribute("BPS_MACRO_CONTEXT", PortletSession.APPLICATION_SCOPE);
sess1.removeAttribute("BPS_MACRO_FILE_DETAILS", PortletSession.APPLICATION_SCOPE);
sess1.removeAttribute("BPS_MACRO_FILE_LIST", PortletSession.APPLICATION_SCOPE);
HttpServletRequest servletRequest = (HttpServletRequest)arg0;
PortletRequest pReq = (PortletRequest)arg0;
HttpServletResponse servletResponse= (HttpServletResponse)arg1;
System.out.println("\n\n Content Type" + servletRequest.getContentType());
try{
if(context != null){
boolean isFileMultipart = ServletFileUpload.isMultipartContent(servletRequest);
System.out.println("\nFILE TO BE UPLOADED IS MULTIPART ? " + isFileMultipart);
if(isFileMultipart){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(servletRequest);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
InputStream iStream = item.getInputStream();
ByteArrayOutputStream ByteArrayOS = new ByteArrayOutputStream();
int sizeofFile =(int) item.getSize();
byte buffer[] = new byte[sizeofFile];
int bytesRead = 0;
while( (bytesRead = iStream.read(buffer, 0, sizeofFile)) != -1 )
ByteArrayOS.write( buffer, 0, bytesRead );
String data = new String( ByteArrayOS.toByteArray() );
int k = 0;
//Check if the file is Refund or Premium
int dynamicArraySize = 0;// = st2.countTokens() * 9;
dynamicArraySize = st2.countTokens() * 9;
if (!item.isFormField() ){
File cfile=new File(item.getName());
String fileName = "";
String separator = "\\";
int pos = item.getName().lastIndexOf(separator);
int pos2 = item.getName().lastIndexOf(".");
if(pos2>-1){
fileName =item.getName().substring(pos+1, pos2);
}else{
fileName =item.getName().substring(pos+1);
File fileToBeUploaded=new File("C:\\Sal\\BPS MACRO\\FileTransfer\\Desti", fileName);
item.write(fileToBeUploaded);
validate.displaySuccessMessage(context);
}catch(Exception e){System.out.println(e);
Logger.debug(this.getClass(), METHOD_NAME, "Leaving BPSMacroPortlet");
super.doView(arg0, arg1);
==== END: doView method in the portle class. ================================
Thanks.one more question. Is there a way where I can submit two forms ?
Thats is submit 2nd form only when the first form is submitted.
I tried this it works.
function formSubmit(){
document.form1.submit();
alert();
document.form2.submit();
But If I dont put an alert(basically it disables the parent page) in between, only the second form is submitted.
If I put a delay of say 3 seconds in between then it will throw a SOCKET CLOSED error in the code triggered due to first form submit.
Thus disabling the paresnt page for a few seconds is reolving my problem.
Any ideas ?
Well Basically when the Alert pop's up the parent page "STALLS" and thus the form2 does not submit till I click on OK, Is there a way I can stall the browser/Parent JSP page using JAVA SCRIPT ??
Edited by: hector on Oct 9, 2007 11:09 AM
Edited by: hector on Oct 9, 2007 2:12 PM -
I was wondering if there's a kind of lightweight component for uploading files in JSF. I tried Oracle's ADF Faces, but besides it being a couple of megs it screwed up the HTML code in my pages and some Javascript functions wouldn't work. I saw a post here where someone created his own component but as it will have minor use in my app i'd like something packed so I can just add it on.
I only need to upload one file in my app, so maybe it's better to use a regular JSP and Servlet approach for this one. Suggestions or comments would be appreciated, thanks..I followed the examples in the chapter, but I needed a .tld file so I created one:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>file</short-name>
<uri>http://java.sun.com/upload</uri>
<display-name>JSF File Upload</display-name>
<description>File upload library fo JSF</description>
<tag>
<name>upload</name>
<tag-class>com.corejsf.UploadTag</tag-class>
<body-content>JSP</body-content>
<description>
Uploads the file.
</description>
<attribute>
<name>value</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>target</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Its in WEB-INF and declared in web.xml, but I'm getting an error:
javax.faces.FacesException: Expression Error: Named Object: 'com.corejsf.Upload' not found.
There's no such class in the component, but the UploadTag returns "com.corejsf.Upload" in both getRenderedType() and getComponentType().
If someone has this working; help please!! -
HELP! File Upload Servlet and Internet Explorer
Hello people. I hope this is an easy problem to solve...
I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
Anyone suggestions?
Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
ERROR MESSAGE:
"HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
root cause
java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.(FileOutputStream.java:176)
java.io.FileOutputStream.(FileOutputStream.java:131)
org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
note The full stack trace of the root cause is available in the Tomcat logs.
Apache Tomcat 5.0.16"
FILE UPLOAD SERVLET source code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.util.*;
public class FileUploadCommons extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("File upload success. <a href=\"/MyWebApp/files/");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletContext sc = getServletContext();
String path = sc.getRealPath("/files");
org.apache.commons.fileupload.DiskFileUpload fu = new
org.apache.commons.fileupload.DiskFileUpload();
fu.setSizeMax(-1);
fu.setRepositoryPath(path);
try {
List l = fu.parseRequest(request);
Iterator i = l.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem)i.next();
fi.write(new File(path, fi.getName()));
catch (Exception e) {
throw new ServletException(e);
out.println("</html>");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doPost(request, response);
HTML PAGE that calls the upload servlet:
<html>
<head>
<title>Example HTML Form</title>
</head>
<body>
<p>Select a file to upload or browse
currently uploaded files.</p>
<form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
method="post" enctype="multipart/form-data">
File: <input type="file" name="file"><br>
<input value="Upload File" type="submit">
</form>
</body>
</html>
Thanks in advance for any assistance.
-DanI'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
String path = sc.getRealPath("/files");
// path is now C:\TOMCAT\webapps\MyWebApps\files\
fi.write(new File(path, fi.getName()));
// append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
So what you want to do is something along the lines of (assuming Windoze):
public static String basename(String filename)
int slash = filename.lastIndexOf("\\");
if (slash != -1)
filename = filename.substring(slash + 1);
// I think Windows doesn't like /'s either
int slash = filename.lastIndexOf("/");
if (slash != -1)
filename = filename.substring(slash + 1);
// In case the name is C:foo.txt
int slash = filename.lastIndexOf(":");
if (slash != -1)
filename = filename.substring(slash + 1);
return filename;
fi.write(new File(path, basename(fi.getName()));
....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ... -
Help with File Upload manually
Hi Experts,
I need code to upload a file without using the upload UI Element. we have our terms and conditions which has to be signed by the user and once the user signs and clicks the next button to go to the next page, I generate a pdf with the time stamp of when the user signed and upload it to ECC. here i can not use the File upload UI Element but have to upload it automatically to ECC.
Can any one help me out with this please.
ThanksHi,
I dont know why you need to to upload the file for this requirement. You can simply store the user id and the timestamp in portal database table or in a ECC z table.
In case you definitely need to upload the file then you can use KM API to uploadthe file to portal KM folder
http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/a099a3bd-17ef-2b10-e6ac-9c1ea42af0e9?quicklink=index&overridelayout=true
but you need not use the upload feature in the example, instead just get the data from wd context and upload to KM.
Srini -
I am facing problem with File Uploding. :(( Could you please provide me some pointers for this.
If possible detailed example is good for me as I am new to JSF
I know how to use Jakartas File Upload Component. Can you provide me some pointers regarding this in JSF.
Thanks
SudhakarI appretiate if you could point me out to the location of file upload component in the JSC. I know how to do it in servlets - just parse mime-multipart stream, but have no idea how to implement file upload/download in the JSC.
Thank you for your help! -
Need Help to integrate ProgressBar in JSF
Hi,
I am using <ui:upload> to upload the file in my JSF application. Now I have to show the ProgressBar when the User clicks on the Upload button to Upload the file.
Can any one tell me, how can I achieve that ?????
If any one can put code over here then it will be great.....
Thanks in advance,
jsfgeeksThanks my dear friend,
That's true but I want to Update my Progress Bar as File upload is in progress till the end of Whole file upload...
For that what kind of parameters I have to set and what kind of function I have to write to change the value of progressBar dynamically...
If you can give answer for this then it will help me alot...
Thanks in advance...
JSFGEEKS -
Need Tutorial about file upload
Hi folks!
Have anybody a link or something else to a tutorial for uploading files with JSF?
And i mean with the "plain" JSF RI 1.2 from Sun. Google gives me a lot of Websites with Apache myFaces and myfaces extensions, but i use facelets.
So i have to bring all the the packages together and to mutch action for my little app.
Greetings, cpt.crispyUsing plain JSF RI 1.2 is not possible to do what you want.That's a pity!
So, you need to use an additional component library
like apache tomahawk.I know that. But what does the "additional component library" do?
Don't misunderstand me please. I want to learn how file uploads works in JSF and J2EE, not to learn some "magic" libraries.
For most Java problems you can get "additional libraries", but sometimes it's better you make it on your own to learn how it works.
Thanks for your reply, cpt.crispy -
Help with file upload Actionscript
I am trying to do a file upload using Actionscript and a
modified version of the tutorial found at:
http://tutorials.lastashero.com/2005/10/creating_a_file_upload_applica.html
When I call the function
fileRef.upload("
http://www.imgthis.com/upload_loader.php");
should that go to that page once it finishes, or how do I
force Flash to redirect the browser to that page passing the
uploaded file?
What am I missing here, or what else would anyone need to
help me?
Any help would be greatly appreciated thanks in advance!
Joshua AbtsIt seems as though the page is not being loaded after the
ActionScript upload command.
Why would my PHP script not be called from the upload
ActionScript? I even just did a simple one line redirect to see if
the PHP script was even being called and it didn't work.
What is the basis for getting the script to send the picture
to the PHP script as a post and using the $_FILES array?
Thanks,
Josh -
Help on File Upload on ATG Dynamo 5.6 (Servlet 2.2)
Hi,
I am using Apache Common FileUpload to upload a file on the server. It works well on Tomcat . I tried to port the same code on ATG Dynamo 5.6.1, I could not upload the files. After going deep into the problem, I got to know that Apache FileUpload has a dependancy of Servlet 2.3 Specs compliance.
While I checked the version of Servlet on ATG, it was 2.2.
Could somebody help me with the same.
I need some file upload utility that would work on ATG Dynamo.
Or atleast a way out would do.
Thanks and regards.....
KalpakTry to obtain an older version of the commons FileUpload utility if available, which is compatible with your desired version or you can use another utility that supports Servlets 2.0 provided by Oreilly Package...
The class MultipartRequest authored by oreilly that included in the package holds the whole nasty behind the scenes, here you are the link for the docs
http://www.stanford.edu/group/coursework/stanfordoki/oreilly/com.oreilly.servlet.MultipartRequest.html
And you can find the package, examples and the sources here
http://examples.oreilly.com/jservlet2/
Best Regards,
mohammed Sleem -
Need Help With File Matching Records
I need help with my file matching program.
Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
Here is my following program code:
// Exercise 14.8: CreateTextFile.java
// creates a text file
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class CreateTextFile
private Formatter output1; // object used to output text to file
private Formatter output2; // object used to output text to file
// enable user to open file
public void openTransFile()
try
output1 = new Formatter("trans.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
output2 = new Formatter("oldmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openOldMastFile
// add transaction records to file
public void addTransactionRecords()
// object to be written to file
TransactionRecord record1 = new TransactionRecord();
Scanner input1 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0) and amount.","? ");
while (input1.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record1.setAccount(input1.nextInt()); // read account number
record1.setAmount(input1.nextDouble()); // read amount
if (record1.getAccount() > 0)
// write new record
output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input1.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
"and amount.","? ");
} // end while
} // end method addTransactionRecords
// add account records to file
public void addAccountRecords()
// object to be written to file
AccountRecord record2 = new AccountRecord();
Scanner input2 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0), first name, last name and balance.","? ");
while (input2.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record2.setAccount(input2.nextInt()); // read account number
record2.setFirstName(input2.next()); // read first name
record2.setLastName(input2.next()); // read last name
record2.setBalance(input2.nextDouble()); // read balance
if (record2.getAccount() > 0)
// write new record
output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
record2.getLastName(), record2.getBalance());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input2.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0),",
"first name, last name and balance.","? ");
} // end while
} // end method addAccountRecords
// close file
public void closeTransFile()
if (output1 != null)
output1.close();
} // end method closeTransFile
// close file
public void closeOldMastFile()
if (output2 != null)
output2.close();
} // end method closeOldMastFile
} // end class CreateTextFile--------------------------------------------------------------------------------------------------
// Exercise 14.8: CreateTextFileTest.java
// Testing class CreateTextFile
public class CreateTextFileTest
// main method begins program execution
public static void main( String args[] )
CreateTextFile application = new CreateTextFile();
application.openTransFile();
application.addTransactionRecords();
application.closeTransFile();
application.openOldMastFile();
application.addAccountRecords();
application.closeOldMastFile();
} // end main
} // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.8: TransactionRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
public class TransactionRecord
private int account;
private double amount;
// no-argument constructor calls other constructor with default values
public TransactionRecord()
this(0,0.0); // call two-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public TransactionRecord(int acct, double amt)
setAccount(acct);
setAmount(amt);
} // end two-argument TransactionRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set amount
public void setAmount(double amt)
amount = amt;
} // end method setAmount
// get amount
public double getAmount()
return amount;
} // end method getAmount
} // end class TransactionRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: AccountRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
import org.egan.TransactionRecord;
public class AccountRecord
private int account;
private String firstName;
private String lastName;
private double balance;
// no-argument constructor calls other constructor with default values
public AccountRecord()
this(0,"","",0.0); // call four-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public AccountRecord(int acct, String first, String last, double bal)
setAccount(acct);
setFirstName(first);
setLastName(last);
setBalance(bal);
} // end four-argument AccountRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set first name
public void setFirstName(String first)
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
return firstName;
} // end method getFirstName
// set last name
public void setLastName(String last)
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
return lastName;
} // end method getLastName
// set balance
public void setBalance(double bal)
balance = bal;
} // end method setBalance
// get balance
public double getBalance()
return balance;
} // end method getBalance
// combine balance and amount
public void combine(TransactionRecord record)
balance = (getBalance() + record.getAmount());
} // end method combine
} // end class AccountRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatch.java
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Formatter;
import java.util.FormatterClosedException;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class FileMatch
private Scanner inTransaction;
private Scanner inOldMaster;
private Formatter outNewMaster;
private Formatter theLog;
// enable user to open file
public void openTransFile()
try
inTransaction = new Scanner(new File("trans.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
inOldMaster = new Scanner(new File("oldmast.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openOldMastFile
// enable user to open file
public void openNewMastFile()
try
outNewMaster = new Formatter("newmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openNewMastFile
// enable user to open file
public void openLogFile()
try
theLog = new Formatter("log.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openLogFile
// update records
public void updateRecords()
TransactionRecord transaction = new TransactionRecord();
AccountRecord account = new AccountRecord();
try // read records from file using Scanner object
System.out.println("Start file matching.");
while (inTransaction.hasNext() && inOldMaster.hasNext())
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
account.setAccount(inOldMaster.nextInt()); // read account number
account.setFirstName(inOldMaster.next()); // read first name
account.setLastName(inOldMaster.next()); // read last name
account.setBalance(inOldMaster.nextDouble()); // read balance
if (transaction.getAccount() == account.getAccount())
while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
account.combine(transaction);
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
else if (transaction.getAccount() != account.getAccount())
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
} // end while
System.out.println("Finish file matching.");
} // end try
catch (NoSuchElementException elementException)
System.err.println("File improperly formed.");
inTransaction.close();
inOldMaster.close();
System.exit(1);
} // end catch
catch (IllegalStateException stateException)
System.err.println("Error reading from file.");
System.exit(1);
} // end catch
} // end method updateRecords
// close file and terminate application
public void closeTransFile()
if (inTransaction != null)
inTransaction.close();
} // end method closeTransFile
// close file and terminate application
public void closeOldMastFile()
if (inOldMaster != null)
inOldMaster.close();
} // end method closeOldMastFile
// close file
public void closeNewMastFile()
if (outNewMaster != null)
outNewMaster.close();
} // end method closeNewMastFile
// close file
public void closeLogFile()
if (theLog != null)
theLog.close();
} // end method closeLogFile
} // end class FileMatch-------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatchTest.java
// Testing class FileMatch
public class FileMatchTest
// main method begins program execution
public static void main( String args[] )
FileMatch application = new FileMatch();
application.openTransFile();
application.openOldMastFile();
application.openNewMastFile();
application.openLogFile();
application.updateRecords();
application.closeLogFile();
application.closeNewMastFile();
application.closeOldMastFile();
application.closeTransFile();
} // end main
} // end class FileMatchTest-------------------------------------------------------------------------------------------------
Sample data for master file:
Master file
Account Number Name Balance
100 Alan Jones 348.17
300 Mary Smith 27.19
500 Sam Sharp 0.00
700 Suzy Green -14.22Sample data for transaction file:
Transaction file Transaction
Account Number Amount
100 27.14
300 62.11
300 83.89
400 100.56
700 80.78
700 1.53
900 82.17 -------------------------------------------------------------------------------------------------
My FileMatch class program above has bugs in it.
The correct results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 173.19
500 Sam Sharp 0.00
700 Suzy Green 68.09The correct results for the log.txt:
Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
My results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 111.08
500 Sam Sharp 0.00
700 Suzy Green -12.69My results for the log.txt
Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
I am not sure what is wrong with my code above to make my results different from the correct results.
Much help is appreciated. Please help.From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do. -
Error while during file upload in JSF
Hi
I do get this error while uploading a file in JSF .
org.apache.myfaces.webapp.filter.MultipartRequestWrapper.parseRequest(MultipartRequestWrapper.java:134)
at org.apache.myfaces.webapp.filter.MultipartRequestWrapper.getParameter(MultipartRequestWrapper.java:163)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:157)
at com.sun.faces.context.RequestParameterMap.get(ExternalContextImpl.java:673)
at jsf.PagePhaseListener.afterPhase(PagePhaseListener.java:18)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:211)
Can anybody wat i must dothanks....
but that answer is not solve my question. Actually i want to know.. can we develope a custom tag in JSF for file upload......
Maybe you are looking for
-
My iTunes application on my computer will not open at all anymore
Alright so everytime i plug my iPod into the computer, the iTunes application opens. It said there was a new update for iTunes and so i started to install it. I was then on google looking up some songs on Youtube. Everything was slow so i decided to
-
What's the difference between "PreparedStatement" and "Statement"?
What's the difference between "PreparedStatement" and "Statement"? Which is better??????
-
Monitor hp pavilion 23xi and wall mount
Good morning everyone, I'm a possessor of an hp pavilion 23xi monitor and i was wondering if there's a way to mount it on a wall, surfing on the web I didn't find anything about my question, does anyone of you mounted the same monitor on a wall? If s
-
View only responsibiliteis in 11.5.8
Can someone please help me ? I am new at this. I want to set up the resposibilities in "view only" mode so that user cann't update the data. Does anyone knoe how to do this? Please let me know. Any help would be appreciated. Nikunj
-
Array of Tab Control page names
Hi, I wish to programatically create an array of the names of the pages within a Tab Control. See the attached VI for my attempt at this. It works, but as it runs it changes which page is displayed on the front panel. Is there a way to do this withou