Uploading a file from form using Jsp to webserver
WE tried to upload a file to a webserver. We tried different ways that we got code from this forum.
but unable to access the data sent from the browser.
Plssss go thro the code and let us know what the problem is.......
<%
try
ServletContext context = getServletContext();
InputStream mySis = request.getInputStream();
out.println(mySis.available());
BufferedReader r = new BufferedReader(new InputStreamReader(mySis));
String line = null;
StringBuffer buf = new StringBuffer();
while ((line = r.readLine())!=null) {
out.println(line);
buf.append(line);
out.println("********PRINT");
out.println(buf.toString());
}catch(Exception ee){out.print("error");}
%>
We also tried the code posted in this forum
InputStream mySis = request.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
do
myCurrentByte = mySis.read();
bos.write(myCurrentByte);
Appreciate ur help.
use the FileUpload package. it's part of the jakarta commons packages. works great, decent docs. I use it in several production systems.
Similar Messages
-
Opening .pdf files from forms using OLE
Hi,
I want to open, print , save and save as pdf files from forms using OLE . Please help me with the same.
Thanks
VidyaIf you are in client/server mode, you can put an OLE container component on your form. However, be warned that this method does not work when you convert to the forms server web enabled mode. If you anticipate moving your application to the web anytime soon, my advice would be to web-enable first and then add in the feature to view .pdf (or other) files. In our client/server app, I went to a lot of trouble to add in OLE features such as you describe, and now I have to completely re-write those features for the web.
-
How to upload a file into server using j2ee jsp and servlet with bean?
How to upload a file into server using j2ee jsp and servlet with bean? Please give me the reference or url about how to do that. If related to struts is more suitable.
Anyone help me please!u don't need j2ee and struts to do file uploading. An example is as such
in JSP. u use the <input> file tag like
<input type="file"....>You need a bean to capture the file contents like
class FileUploadObj {
private FormFile srcFile;
private byte[] fileContent;
// all the getter and setter methods
}Then in the servlet, you process the file for uploading
* The following loads the uploaded binary data into a byte Array.
FileUploadObj form = new FileUploadObj();
byte[] byteArr = null;
if (form.signFile != null) {
int filesize = form.srcFile.getFileSize();
byteArr = new byte[filesize];
ByteArrayInputStream bytein = new ByteArrayInputStream (form.srcFile.getFileData());
bytein.read(byteArr);
bytein.close();
form.setFileContent(byteArr);
// Write file content using Writer class into the destination file in the server.
... -
Uploading a file from jsp page on weblogic portal 9.2 into VCR content node
I am working on Content Management in Weblogic Portal 9.2 using the com.bea.content API. I have succedded to the extent that I have created "Node" both Hierarchy and Content Node in the Virtual Content Repository using the CM API from a JSP.
Now I have to upload a file from this JSP into VCR Content Node. I am facing some problems. I am not able to figure out which class to use for this purpose from CM API. Please help in this regard.Hi,
You need to ensure you're using an ObjectClass with a PropertyDefiition of type Property.BINARY. Then, construct a BinaryValue with your InputStream. Use that to construct the Value and Property for the Node you're creating or updating.
-Ryan -
Upload xml file from aplication server using read dataset, parser error.
Hi,
I would like to upload xml file from app. server but parser failed. If I upload this xml file from workstation (using ws_upload) it is correct. For uploading xml file from app. server I use open dataset... read dataset. In loop section I remove '#' char. How do You upload xml file from app server? What Could be incorrect.
I try to open dataset in binary mode, text mode...
TYPES: BEGIN OF xml_line,
data(255) TYPE c,
END OF xml_line.
DATA: gt_xml_table TYPE TABLE OF xml_line,
gs_xml_structure TYPE xml_line,
gv_xml_table_size TYPE i.
OPEN DATASET s FOR INPUT IN BINARY MODE.
IF sy-subrc <> 0.
MESSAGE e001(zet) WITH '....'.
ENDIF.
DO.
READ DATASET s INTO gs_xml_structure.
IF sy-subrc <> 0.
EXIT.
ELSE.
len = STRLEN( gs_xml_structure ).
len = len - 1.
check len > 0.
WRITE gs_xml_structure(len) TO gs_xml_structure.
APPEND gs_xml_structure TO gt_xml_table.
ENDIF.
ENDDO.You Can do this too
parameters: p_file like rlgrap-filename.
data: subrc like sy-subrc.
create object me.
REFRESH t_data.
* Open XML File
CALL METHOD me->CREATE_WITH_FILE
EXPORTING
filename = p_file
RECEIVING
retcode = subrc.
* Saves Data in an itab from XML File.
CALL METHOD me->get_data
IMPORTING
retcode = subrc
CHANGING
dataobject = t_data[].
Regards,
Claudio. -
To upload a file from client machine to server machine
Hi everybody!
Could anyone plz help me. I am struck in a problem
I want to transfer a file from client's machine to server but I am not able to upload
It is tranferring the file only to the local machine
I am using orielley package It is transferring files only to my local machine but not to the server .Can anyone correct it. It's very urgent
how to write the relative path for server
I am using this path and it is not uploading
MultipartRequest multi = new MultipartRequest(request, "../<administrator>:<dev2daask>@dev2:C:/123data/", 5 * 1024 * 1024);
Here is my code:
<%@ page import="java.util.*" %>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="java.io.*" %>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%
try {
// Blindly take it on faith this is a multipart/form-data request
// Construct a MultipartRequest to help read the information.
// Pass in the request, a directory to saves files to, and the
// maximum POST size we should attempt to handle.
// Here we (rudely) write to the server root and impose 5 Meg limit.
MultipartRequest multi = new MultipartRequest(request, "../<administrator>:<dev2daask>@dev2:C:/123data/", 5 * 1024 * 1024);
out.println("<HTML>");
out.println("<HEAD><TITLE>UploadTest</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>UploadTest</H1>");
// Print the parameters we received
out.println("<H3>Params:</H3>");
out.println("<PRE>");
Enumeration params = multi.getParameterNames();
while (params.hasMoreElements()) {
String name = (String)params.nextElement();
String value = multi.getParameter(name);
out.println(name + " = " + value);
out.println("</PRE>");
// Show which files we received
out.println("<H3>Files:</H3>");
out.println("<PRE>");
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
out.println("name: " + name);
out.println("filename: " + filename);
out.println("type: " + type);
if (f != null) {
out.println("length: " + f.length());
out.println();
out.println("</PRE>");
catch (Exception e) {
out.println("<PRE>");
out.println("</PRE>");
out.println("</BODY></HTML>");
%>you have not understood my point
how does this code will run on servlet when I want to upload a file from client's
machine to server machine
what I am doing is I am giving an option to the user that he/she can browse the file and then select any file and finally it's action is post in the jsp form for which I have sent the code
All the computers are connected in LAN
So how to upload a file from client's machine to server's machine
Plz give me a solution -
Uploading a file to server using ajax and struts
My problem is i wrote a program to upload a file to the server using Ajax.
Here iam used Struts and Ajax.
The problem is when iam uploaded a file from my PC the file is uploading to the server in the upload folder located in the server my system.
Iam using Tomcat server 5.0
But when iam trying to access it through other system it is not doing so
Giving an internal server error i,e 500.
Iam putting the necessary documents for ur reference.
Plz help me soon .
My exact requirement is i have to upload a file to the upload folder located in the server.
And i have to get the path of that file and display the file path exactly below the browse button from where iam uploaded a file.
That should be done without page refresh and submit thats y iam used Ajax
Any help would greatly appreciated
Thanks and Regards
Meerasaaheb.
The action class is FilePathAction
package actions;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FilePathAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
String contextPath1 = "";
String uploadDirName="";
String filepath="";
System.out.println(contextPath1 );
String inputfile = request.getParameter("filepath");
uploadDirName = getServlet().getServletContext().getRealPath("/upload");
File f=new File(inputfile);
FileInputStream fis=null;
FileOutputStream fo=null;
File f1=new File(uploadDirName+"/"+f.getName());
fis=new FileInputStream(f);
fo=new FileOutputStream(f1);
try
byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
int len = -1;
while((len = fis.read(buf)) != -1)
fo.write(buf, 0, len);
catch(Exception e)
e.printStackTrace();
filepath=f1.getAbsolutePath();
request.setAttribute("filepath", filepath);
return mapping.findForward("filepath");
the input jsp is
filename.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
alertflag = false;
var xmlHttp;
function startRequest()
if(alertflag)
alert("meera");
xmlHttp=createXmlHttpRequest();
var inputfile=document.getElementById("filepath").value;
xmlHttp.open("POST","FilePathAction.do",true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send("filepath="+inputfile);
function createXmlHttpRequest()
//For IE
if(window.ActiveXObject)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
//otherthan IE
else if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
return xmlHttp;
//Next is the function that sets up the communication with the server.
//This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
function handleStateChange()
var message=" ";
if(xmlHttp.readyState==4)
if(alertflag)
alert(xmlHttp.status);
if(xmlHttp.status==200)
if(alertflag)
alert("here");
document.getElementById("div1").style.visibility = "visible";
var results=xmlHttp.responseText;
document.getElementById('div1').innerHTML = results;
else
alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
</script></head><body><form name="thumbs" enctype="multipart/form-data" method="post" action="">
<input type="file" name="filepath" id="filepath" onchange="startRequest();"/>
</form>
<div id="div1" style="visibility:hidden;">
</div></body></html>
The ajax response is catching in a dummy.jsp
<%=(String)request.getAttribute("filepath")%>
corresponding action mapping
<action path="/FilePathAction" type="actions.FilePathAction">
<forward name="filepath" path="/dummy.jsp"/>
</action>
So plz help me to upload a file to the server from any PC.
Iam searched alot but didnt get any solution.Plz help me soon if it possible so
Iam in great need.
I have worked alot but not worked out.
Any help greatly appreciated -
Uploading a file from a J2ME application
Ok, obviously this is either not interesting, or no one really knows what to do, I would love any ideas even if they dont work, just anything that would help would be great :)
I am extremely new to servlet programming and reasonably new to J2ME. I want to upload a file from my device to a central server. I am not sure how to go about starting this. I have a html form that requests a file and posts it to the servlet fine, but I am not sure how I would get my J2ME application to do the same. Do I replicate the html from with in the program? Any help would be much appreciated.
My basic servlet and Java code is:
Java
public String sendPostRequest(String urlstring) throws IOException {
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
String message = "";
// the request body
FileSystem fs = new FileSystem();
byte[] file = fs.returnFile("c:/other/dot/helloworld.txt");
if(file != null){
String fileString = ("file=" + new String(file));
try {
// an HttpConnection with both read and write access
hc = (HttpConnection)Connector.open(urlstring, Connector.READ_WRITE);
// set the request method to POST
hc.setRequestMethod(HttpConnection.POST);
// set request type
// Could possibly need to be "application/x-www-form-urlencoded"????????????????????????????????
hc.setRequestProperty("Content-Type", "multipart/form-data");
hc.setRequestProperty("Content-Length", fileString.length()+ "" );
// obtain DataOutputStream for sending the request string
dos = hc.openDataOutputStream();
byte[] requestBody = fileString.getBytes();
// send request string to Web server
for (int i = 0; i < requestBody.length; i++) {
dos.writeByte(requestBody);
// flush it out
dos.flush();
// obtain DataInputStream for receiving server responses
dis = new DataInputStream(hc.openInputStream());
// retrieve the responses from Web server
int ch;
while ((ch = dis.read()) != -1) {
message = message + (char) ch;
} finally {
// free up i/o streams and http connection
if (hc != null)hc.close();
if (dis != null)dis.close();
if (dos != null)dos.close();
Servlet
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.oreilly.servlet.MultipartRequest;
public class DNTUpload extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try{
MultipartRequest multi = new MultipartRequest(req, "C:\\Servlets+JSP\\DNT", 5*1024*1024);
Enumeration files = multi.getFileNames();
String name = (String)files.nextElement();
File f = multi.getFile(name);
if(f != null){
out.println("<HTML>");
out.println("<HEAD><TITLE>FileUploader</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Should have saved file</H1>");
out.println("</BODY>");
out.println("</HTML>");
else{
res.setHeader("valserror", "ERROR");
}catch(Exception e){
out.println("<HTML>");
out.println("<BODY>");
out.println("failure!!");
out.println("</BODY>");
out.println("</HTML>");
Message was edited by:
-fluffy-I've only done one small j2me program and not recently, but here is a link that can give you some of the basics: http://today.java.net/pub/a/today/2005/02/09/j2me1.html
I'm guessing, but I believe you have to use http sockets to accomplish a file transfer with a phone. Also, there are some limitations with full sockets depending on which type of phone you using to write your app to.
Hope that helps! -
How to upload a file from java to php
hi
i am trying to upload/send a file from client using swing/applet
and receiving it with php code.
here is the php code which uploads the post file from the client
$uploaddir = "/home/raghavendra/Documents/";
$file = basename( $_FILES["uploadedfile"]["name"]);
echo "file:\n".$file;
$uploadfile = $uploaddir. $file;
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"],$uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
else {
echo "File upload failure Possible file upload attack!\n";
and corresponding different java code which post the
1)
public void postmethodTest(String filefrom){
try{
String hostname = "localhost";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
// Send header
String path ="/php_prgs/var/www/nsboxng/htdocs/tryupdate.php";
File theFile = new File(filefrom);
System.out.println ("size: " + (int) theFile.length());
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(theFile)));
byte[] theData = new byte[(int) theFile.length( )];
fis.readFully(theData);
fis.close();
DataOutputStream raw = new DataOutputStream(socket.getOutputStream());
Writer wr = new OutputStreamWriter(raw);
String command =
"POST "+path+" HTTP/1.0\r\n"
+ "Content-type: multipart/form-data, boundary=mango\r\n"
+ "Content-length: " + ((int) theFile.length()) + "\r\n"
+ "\r\n"
+ "--mango\r\n"
+ "content-disposition: name=\"MAX_FILE_SIZE\"\r\n"
+ "\r\n"
+ "\r\n--mango\r\n"
+ "content-disposition: attachment; name=\"datafile\"" ;
String filename="test.doc\"\r\n"
+ "Content-Type: text/doc\r\n"
+ "Content-Transfer-Encoding: binary\r\n"
+ "\r\n";
wr.write(command);
wr.flush();
raw.write(theData);
raw.flush( );
wr.write("\r\n--mango--\r\n");
wr.flush( );
BufferedReader rd = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("out"+line);
wr.close();
raw.close();
socket.close();
} catch (Exception e) {System.out.println(e.toString());}
2)
public void postMethod(String strURL, String filefrom){
try {
String fname = filefrom.substring(filefrom.lastIndexOf("/")+1, filefrom.length());
File input=new File(filefrom);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
// Specify content type and encoding
// If content encoding is not explicitly specified
// ISO-8859-1 is assumed
//post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
post.setRequestHeader("Content-Type","multipart/form-data");
post.setRequestHeader("Content-Disposition", "form-data; name="+fname);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result=httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " +result);
// Display response
System.out.println("Response body: ");
// System.out.println(post.getResponseBodyAsString());
BufferedReader console = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
String name = null;
String line = null;
try {
while ((line = console.readLine()) != null) {
System.out.println("output"+line);
//name = console.readLine();
catch (IOException e) { name = "<" + e + ">"; }
// System.out.println("Hello " + name);
} finally {
// Release current connection to the connection pool
// once you are done
post.releaseConnection();
catch(IOException e){
but am getting else condition response from php code
but if i post with html code it is working fine.
can anybody help me please where i have to change the code
please suggest me. am in a big trouble and i have to complete this as soon as possibleJakarta Commons HttpClient
~ -
Uploading a file to server using servlet (Without using Jakarta Commons)
Hi,
I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
From
Velu<p>Why put such a restriction on the solution? Whats wrong about using that library?
The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
I was with the view that the same can be implemented by our own code right? -
How to get the complete path name when uploading a file from servlet
Hi,
I write a servlet to upload a file from html page
<intput type=file name=fileupload>I am using
import org.apache.commons.fileupload.to upload file. i want to get the all fields in the form and file name and content of the file also.
It give the file name only
String filename= fileItem.getName();
o/p krish.jpgBut i want complete path naem like
d:/krishna/images/funny/krish.jpgI serach the API org.apache.commons.fileupload.*
But i did nt find the method to get it.
plz help me , which api or method to use here..Krishna_Rao_chintu wrote:
But i need path and have to do some calculations on it.No, you don't. If you have requirements which say you do then the requirements are wrong. You couldn't do anything useful with the path on the client system even if you could get it.
is there any alternatives in java
I need path and have to calculate MD5, Presumably you need to calculate MD5 on the contents of the file and not on the name of the file.
and convert the file to binary format.... etc oprations on itSorry, "convert a file to binary format" is basically meaningless.
but we can get the content of the file using
byte [] get()/ getString() methods
If i get content is there any performance degrades?
ie if the content is lengthy is it take more time?Take more time than what? Degrading performance from what? It's certainly true that it would be quicker to not upload the file, but that's a pointless comparison. If you have some other process to compare with, let us know what it would be. -
firefox 7.0 - Can not upload the file from local machine to server...gives "error 404 : file not found"
you have not understood my point
how does this code will run on servlet when I want to upload a file from client's
machine to server machine
what I am doing is I am giving an option to the user that he/she can browse the file and then select any file and finally it's action is post in the jsp form for which I have sent the code
All the computers are connected in LAN
So how to upload a file from client's machine to server's machine
Plz give me a solution -
Urgent - Upload a file from Client to Server.
Need to load a file from the client machine to the Server running 9iAS Rel. 1 on a HP Unix Machine.
We are using Forms 6i. We have looked into the File Upload Utility demo code provided with Forms 6i - but have been unsuccessful in reusing it. PLS HELPDuplicate post.
Upload a file from client to server by forms in E-Bussiness Suite R12
Re: Upload a file from client to server by forms in E-Bussiness Suite R12. -
How does one upload a file from flex to a cfc
How does one upload a file from flex to a cfc? Can you do the file upload via remote object? I usually do uploads cia cfm but prefer the asnc capabilities of remote object calls.
Hi,
The issue here is myFile. For flex we need to pass this name as paramenter becuase it's not html form item like:
<cfcomponent>
<cffunction name="uploadFile" access="remote" output="false" returntype="void">
<cfargument name="file" required="Yes" type="any">
<cffile action="upload" filefield="#arguments.file#" destination="C:\temp\" nameconflict="makeunique">
</cffunction>
</cfcomponent>
From flex I'm getting the file using fileReference like:
private function browseAndUpload():void
fileReference = new FileReference();
fileReference.addEventListener(Event.SELECT,fileReference_Select);
fileReference.addEventListener(Event.CANCEL,fileReference_Cancel);
fileReference.browse();
private function fileReference_Select(event:Event):void
fileReference.addEventListener(ProgressEvent.PROGRESS,fileReference_Progress);
fileReference.addEventListener(Event.COMPLETE,fileReference_Complete);
fileReference.addEventListener(IOErrorEvent.IO_ERROR,onLoadError);
//fileReference.upload(request);
fileName = fileReference.name;
myFile.htmlText = fileReference.name;
SM_RO.importNSA();
filerReference have an upload method to upload the file but I can't use that becuase I need to process my upload with my cfc.
I'm getting an error:
Failed to import the file. The cffile action="upload" requires forms to use enctype="multipart/form-data". Please also make sure the file is not open.
I can't find the way to setup the enctype becuase again i can have html form items in flex, or I can?
Thanks
Johnny -
Upload XL file from FTP server
Hi All,
Can anybady help me, how to upload Excel file from FTP server.
Thanks
Sri
Edited by: srikanthn on Apr 14, 2010 6:31 PMHello
How about using SAPFTP?
I hope SAP note 130106 will guide you on this.
Thanks
koju
Maybe you are looking for
-
How do yo get a HP ENVY 7000 to display on a DEL monitor. Z . vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
-
Randomly Shutting Off When On Battery Power
So, I recently had my logic board replaced because my built-in audio out port wasn't working. I had this done more than a week ago, but just 2 days ago I was using it without being plugged in for over an hour (the battery indicator said I had about 5
-
Row-base security : how to filter on a set of value ?
Hello all! I am currently trying to setup the row-based security in OBIEE and I am facing some difficulties, not sure if they are basic or not: I'd like my users or groups to access data depending on a list of value. I know the best practice is to cr
-
any solution for this one.
-
I am having a fiber for internet converted to ethernet using ISP's media convertor . Now that media convertor is not that good and hangs sometimes . Edge equipment is ASA and if I need to put fiber there I would require to puchase SSM-4GE which is qu