CodeCharge Studio
search Register Login  

Visual PHP Web Development

Visually Create Internationalized Web Applications, Web Reports, Calendars, and more.
CodeCharge.com

YesSoftware Forums -> CodeCharge Studio -> Java

 Java/JSP file upload

Print topic Send  topic

Author Message
Arumugam
Posted: 02/09/2005, 10:44 PM

First i am getting Input txt file through core java.,

This getting input file i need to send the JSP page.

i need the solution., anybody i help to me.,
Rajitha
Posted: 02/11/2005, 8:18 AM

:-<

I am trying to upload image files using JSP and Servlets. I am using Jakarta common file upload. For the images less than 16MB this works perfect. But when I try to upload images larger than 16MB it is not working.

I tried to use Oreilly MultiParseRequest also. The problem is for larger images when I try to read request.getInputStream().read() it always returns -1 and displaying paeg cannot be displayed error.

I tired this with tow simple jsps. Even getting the same problem. Can anyone help me on this?

Regards,
Rajitha
Deepak
Posted: 02/11/2005, 8:14 PM

:-/
I need to upload file to a specified directory on the server.
So how would i mention in my jsp to save a particular file to specified directory.
Thanks in Advance
Deepak Singh
krishnanand
Posted: 02/16/2005, 10:23 PM

Hi evr1!
Can any one of you help me out in file uploading I dont want to use any external jar files,It should be of java code with jsp.
file to be uploaded is pdf, txt ,excel ,doc or image
in oracle with blob datatype.I'm able to do in folder which is not required.
kindly help me out.
Prabhakar
Posted: 02/21/2005, 5:05 AM

Quote :
Hi_every_Body!


I need a jsp program that translates a web page by making use of the

online internet services like translate.google or bayfish or other

please guide.......
Balaji
Posted: 02/21/2005, 5:47 AM

Hi,
friends pls let me know about image upload into database.even i've tried the above code.but the error likes .......

MultipartRequset cannot be resolved or is not a type

pls help me.this is urgent
Thanks in advance.
Balaji
Posted: 02/21/2005, 6:02 AM

Hi friends,
when i tried to run the above code(file upload), the file saved into tomcat/bin dir. but i need to save image into Database.how to do that.
pls help me.
Regards,
Balaji
kushal
Posted: 02/24/2005, 2:04 AM

Please tell me where do i find that com.oreilly package ?
(i allready search on oreilly site)
Rohit
Posted: 02/24/2005, 5:28 AM

i have written a file to a disk and have problem in uploading the file could anyone please help me
Thnaks regards
Rohit
girish
Posted: 03/02/2005, 6:55 AM

Quote Roger:
Hi,

Are there any java/JSP examples of the file upload?

R.
eserver220

Posts: 41
Posted: 03/02/2005, 5:29 PM

I have got a workable example! I'd like to share it with all of you.
I have no time to translate the comment in the .java file into english, but I think you have no need to understand it. Just compile the code and integrate it in your project.

--FileUploadBean.java
package FileUploadBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import java.util.Dictionary;
import java.util.Hashtable;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.*;

public class FileUploadBean {

private String savePath, filepath, filename, contentType;
private byte[] b;
byte t;
private Dictionary fields;

public String getFilename() {
return filename;
}


public String getFilepath() {
return filepath;
}


public void setSavePath(String savePath) {
this.savePath = savePath;
}



public String getContentType() {
return contentType;
}



public String getFieldValue(String fieldName) {
if (fields == null || fieldName == null)
return null;
return (String) fields.get(fieldName);
}



private void setFilename(String s) {
if (s==null)
return;
int pos = s.indexOf("filename=\"");
if (pos != -1) {
filepath = s.substring(pos+10, s.length()-1);
// Windowsä¯ÀÀÆ÷·¢ËÍÍêÕûµÄÎļþ·¾¶ºÍÃû×Ö
// µ«Linux/UnixºÍMacä¯ÀÀÆ÷Ö»·¢ËÍÎļþÃû×Ö
pos = filepath.lastIndexOf("\\");
if (pos != -1)
filename = filepath.substring(pos + 1);
else
filename = filepath;
}

}

private void setContentType(String s) {
if (s==null)
return;
int pos = s.indexOf(": ");
if (pos != -1)
contentType = s.substring(pos+2, s.length());
}



public void getByte(HttpServletRequest request){
DataInputStream is;
int i=0;
try {
is=new DataInputStream(request.getInputStream());
b=new byte[request.getContentLength()];
while (true){
try {
t=is.readByte();
b=t;
i++;
}catch(EOFException e)
{ break;}
}
is.close();}
catch(IOException e) {}

}


public void doUpload1(HttpServletRequest request) throws IOException {

byte[] line=new byte[128];
FileOutputStream os=new FileOutputStream("c:\\Demo.out");
ServletInputStream in = request.getInputStream();
getByte(request);
String temp="";
temp=new String(b,"ISO8859_1");
byte[] img=temp.getBytes("ISO8859_1");

for (int i=0;i<img.length;i++)
{ os.write(img); }
os.close();
}


public void doUpload(HttpServletRequest request) throws IOException {
request.setCharacterEncoding("GB2312");
ServletInputStream in = request.getInputStream();
byte[] line = new byte[1280];
int i = in.readLine(line, 0, 1280);
if (i < 3)
return;
int boundaryLength = i - 2;
String boundary = new String(line, 0, boundaryLength); //-2¶ªÆú»»ÐÐ×Ö·û
fields = new Hashtable();

while (i != -1) {
String newLine = new String(line, 0, i);
if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
if (newLine.indexOf("filename=\"") != -1) {
setFilename(new String(line, 0, i-2));
if (filename==null)
return;

//ÎļþÄÚÈÝ

i = in.readLine(line, 0, 1280);
setContentType(new String(line, 0, i-2));
i = in.readLine(line, 0, 1280);

//¿ÕÐÐ
i = in.readLine(line, 0, 1280);
newLine = new String(line, 0, i,"ISO8859_1");
FileOutputStream pw=new FileOutputStream((savePath==null? "" : savePath) + filename);
//PrintWriter pw = new PrintWriter(new BufferedWriter(new
//FileWriter((savePath==null? "" : savePath) + filename)));
while (i != -1 && !newLine.startsWith(boundary)) {
// ÎļþÄÚÈݵÄ×îºóÒ»Ðаüº¬»»ÐÐ×Ö·û
// Òò´ËÎÒÃDZØÐë¼ì²éµ±Ç°ÐÐÊÇ·ñÊÇ×î
// ºóÒ»ÐÐ
i = in.readLine(line, 0, 1280);
if ((i==boundaryLength+2 || i==boundaryLength+4) && (new String(line, 0, i).startsWith(boundary)))
pw.write(newLine.substring(0, newLine.length()-2).getBytes("ISO8859_1"));
else
pw.write(newLine.getBytes("ISO8859_1"));
newLine = new String(line, 0, i,"ISO8859_1");
}
pw.close();
}
else {
// ÆÕͨ±íµ¥ÊäÈëÔªËØ
// »ñÈ¡ÊäÈëÔªËØÃû×Ö
int pos = newLine.indexOf("name=\"");
String fieldName = newLine.substring(pos+6, newLine.length()-3);
i = in.readLine(line, 0, 1280);
i = in.readLine(line, 0, 1280);
newLine = new String(line, 0, i);
StringBuffer fieldValue = new StringBuffer(1280);
while (i != -1 && !newLine.startsWith(boundary)) {
// ×îºóÒ»Ðаüº¬»»ÐÐ×Ö·û
// Òò´ËÎÒÃDZØÐë¼ì²éµ±Ç°ÐÐÊÇ·ñÊÇ×îºóÒ»ÐÐ
i = in.readLine(line, 0, 1280);
if ((i==boundaryLength+2 || i==boundaryLength+4) && (new String(line, 0, i).startsWith(boundary)))
fieldValue.append(newLine.substring(0, newLine.length()-2));
else
fieldValue.append(newLine);
newLine = new String(line, 0, i);
}
fields.put(fieldName, fieldValue.toString());
}
}
i = in.readLine(line, 0, 1280);
}

}

}


--jsp1.jsp

<%@ page contentType="text/html;charset=gb2312"%>
<jsp:useBean id="TheBean" scope="page" class="FileUploadBean.FileUploadBean" />
<%
TheBean.setSavePath("d:\\");
TheBean.doUpload(request);
out.println("Filename:" + TheBean.getFilename());
out.println("<BR>ContentType:" + TheBean.getContentType());
out.println("<BR>Author:" + TheBean.getFieldValue("author"));
out.println("<BR>Company:" + TheBean.getFieldValue("company"));
out.println("<BR>Comment:" + TheBean.getFieldValue("comment"));
%>

-- jload.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>File Upload Demo </title>
</head>
<body>
<form action=jsp1.jsp enctype="MULTIPART/FORM-DATA" method=post>
Author: <input type=text name=author>
<br>
Company: <input type=text name=company>
<br>
Comment : <textarea name=comment></textarea>
<br>
Choose the upload file <input type=file name=filename>
<br>
File description : <input type=text name=description>
<br>
<input type=submit value="Upload">
</form>
</body>
</html>

By the way, the charset in my file was set to gb2312, you should change it according to your working enviroment.
View profile  Send private message
sivapandiyan
Posted: 03/03/2005, 4:57 AM

sir,
i have a form to upload a file

<FORM ACTION="Foo.do" enctype="MULTIPART/FORM-DATA" METHOD=POST>

name <input type=text name="name"><br>

file <input type=file name="file"><br>

<input type="submit" value="Submit"><br>

</FORM>

The file following code uploads the file fine but i am unable to get the value of text field using request.getParameter("name") in jsp.
It returns null. Please help me solve this. i am using Tomcat 5.0 server.

i also use the code. it is working.but
<!-- upload.jsp -->
<%@ page import="java.io.*" %>

<%
String contentType = request.getContentType();
System.out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}

String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

//out.print(dataBytes);

int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//out.println(boundary);
int pos;
pos = file.indexOf("filename=\"");

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", pos) + 1;


int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

FileOutputStream fileOut = new FileOutputStream(saveFile);


//fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

out.println("File saved as " +saveFile);

}
%>


ram
Posted: 03/03/2005, 4:59 AM

dfjhgj
Chernobyl
Posted: 03/06/2005, 6:44 PM

OK, I have been extensively researching Java File Upload and I have it worked out. It's a big tech mess, so sit down and buckle up.

Step 1 - Client page / JSP code. Simple, most everybody figured out already that the form element must specify enctype="multipart/form-data" method="post" and contain an input element specified as type="file". Therein lies the ugly bit, but we'll be back.

Step 2 - Server side / JSP Java scriptlet. The posted code snippets are great, but they overlook something recently pointed out, that the other elements of the form will no longer appear in the request. There's a good reason for this, but it is far from pretty.

So, when the client (web browser) sends the file as part of the HTTP request to the servlet, it has to assemble all that form information together with the file. Since the encoding type is set to multipart/form-data, this tells the server to expect the body of the HTTP request to contain all of the form data - INCLUDING the other form fields.

So, to this messy code; there is a bit like this

int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());

that finds the HTTP request MIME content boundary. "Multipart" means that each part has to be seperated; the client will create a text 'boundary' to seperate each field. This code identifies that boundary text. (See my silly example request.) Next, there is:

int pos;
pos = file.indexOf("filename=\"");

Boom, the problem in full glory! Above the bit in the HTTP request text that contains the sepcified "filename=\"" text, are some of those boundaries. The actual request might look like this:

POST HTTP1.1 <url>
... etc.. many HTTP headers
Content-Type: multipart/form-data;Boundary=--Some-unique-ID--
.... more HTTP headers, then a blank line

--Some-unique-ID--
Content-Type=text/plain
Name=text_field_name
... other similar header identifiers
... then a blank line, followed by the content

Desired_filename.jpg
--Some-unique-ID--
content-type=image/jpeg
filename=client_side_filename.jpg
... two more header IDs appear after the filename
.... and that is why the code skips past three newlines, including this blank line

<<the binary data starts here>>
<<this is the data dumped to file by the old code>>
<<and runs until you see another>>
--Some-unique-ID--

So, that is why the other fields vanish: they are submitted with the file. You would have to alter the code to also search for your fields. The above code completely skips the part in the header that includes the contents of the text box ("Desired_filename.jpg") and heads straight into the file download.

Try doing a flat dump of ALL the bytes recieved; this should give some insight into what clients are expected to send to the server.

Hope all this helps; it took me many hours and several books to figure it all out. Remember, client-server programming is more than a hobby, it's an obsession. :-P
Siomara Pantarotto
Posted: 03/07/2005, 6:43 AM

Quote pimms:
This is a fileupload.html which I have created:

<form method="post" ACTION="fileupload.jsp" name="upform" ENCTYPE='multipart/form-data'>


<input type="file" name="uploadfile">
<p>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Reset" value="Reset">
<input type="hidden" name="action" value="upload">

</form>
;-) ;-)

The code is very good. Simple and clear. I tried and it worked perfect at once. Now ...can you send me the fileupload.jsp???
Thanks

Siomara
shyam
Posted: 03/09/2005, 9:59 PM

I want to upload a image using jsp in to my webapps directory in the tomcat how is it possible
deepti
Posted: 03/10/2005, 2:04 AM

Quote Kate:
Hi
I am trying to upload file from cleint machine to the database in the server side using Java.I have to give it a name and ID before saving it to the database. I am also using Tomcat.I am a novice in this field.
Any suggestion,direction or sample would be a great help and would be greatly appreciated.
Thanks
Kate:-/
sandesh
Posted: 03/16/2005, 4:54 AM

Quote Roger:
Hi,


Are there any java/JSP examples of the image file upload?

Regards
sandesh kotangale
akhil
Posted: 03/16/2005, 6:18 AM

Thanks Raheel Rehman.
The code haas worked without a single error. Kindly send me a code for uploading multiple files
nem
Posted: 03/30/2005, 1:00 PM

luana_arch or anyoby
how to set an different path to save file ...

thanks in advance for replies
nem
sitanshu
Posted: 04/08/2005, 5:26 AM

hello!

can i get simple file upload and download program ?? if anyone can help me i will be highly thankful >>

hope i will get the response soon>>

thanks


quote=Roger]
Hi,

Are there any java/JSP examples of the file upload?

R.
SITANSHU
Posted: 04/08/2005, 6:39 AM

hello! frens

pls help me out with code for file upload and download and even after tht how to get the path of file which has been uploaded??

as this is also a problem tht how to know tht where file is getting uploaded ??

i will be highly thankful .
ngolong
Posted: 04/08/2005, 7:54 PM

Dear all
I have a problem. My storage folder is myweb/uploads. I want to upload and save files into here but I can not get the path to save it. Because I don'n want to use the path as "C:\\Program Files\\....\\myweb\\uploads".

The root of Apache Tomcat 4.1 is "C:\Windows\system32" when using FileOutputStream to write data.

I hope anyone help me to solve this problem
vibs
Posted: 04/09/2005, 3:46 AM

hi to all
well i am working on a JSP project in which i need to save a HTML page using the JSP code. that is as soon as the user clicks on a submit button the page should be saved on a specified location
please help, thanks in advance
vibs
srikanth
Posted: 04/11/2005, 3:12 AM

Hai Ramesh Kumar Swarnkar

Great work from you I have tried ur code but i need to store the file in specfied path So please do help me
piyush
Posted: 04/12/2005, 11:28 AM

Quote phani:
Quote Thuanvd:
I want to have a code for upload image with jsp/servlet



<%@ page import="java.sql.*,java.io.*,java.util.*,com.oreilly.servlet.MultipartRequest,com.microsoft.jdbc.sqlserver.SQLServerDriver;"%>
<%

/* The Following Code is Used To Insert An Image Into Database

String filename="";
try
{
MultipartRequest multi= new MultipartRequest(request,"d:/phani",5*1024*1024);
Enumeration files=multi.getFileNames();
File f=null;
while(files.hasMoreElements())
{
String name=(String)files.nextElement();
filename=multi.getFilesystemName(name);
String type=multi.getContentType(name);
f=multi.getFile(name);
System.out.println("The File is "+f);
}
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://172.21.1.11:1740;databasename=pubs","sa","satest");
Statement stmt = con.createStatement();
System.out.println("2 "+f);
InputStream is = new FileInputStream(f);
System.out.println("4 "+is);
byte b[]=new byte[is.available()];
is.read(b);
String sql = "INSERT into photo_test (\"Photo\") values('" + b + "')";
System.out.println("sql is " +sql);
stmt.execute(sql);
stmt.close();

}catch(Exception e)
{
System.out.println(e);
}
out.println("The Image is Added into Database");

nidhi
Posted: 04/12/2005, 7:17 PM

I just used the code mentioned here for inserting an image into database but
gives me error as invalid hex number I am not understanding why it is giving such error.I have prepared table as you have mentioned with photo datatype as Blob
Krishna
Posted: 04/12/2005, 11:32 PM

Quote Krishna:
You would not want to upload a image into the database.
What if the image is large ?
Also retrieving the image would be a problem too.
Krishna
Posted: 04/12/2005, 11:42 PM

Quote anil:
Quote Roger:
Hi,

Are there any java/JSP examples of the file upload?

R.

Krishna
Posted: 04/12/2005, 11:42 PM

Quote anil:
Quote Roger:
Hi,

Are there any java/JSP examples of the file upload?

R.

First Prev Page 3 of 5  Next Last


Add new topic Subscribe to topic   


These are Community Forums for users to exchange information.
If you would like to obtain technical product help please visit http://support.yessoftware.com.

PHP Reports

Visually create Web Reports in PHP, ASP, .NET, Java, Perl and ColdFusion.
CodeCharge.com

Home   |    Search   |    Members   |    Register   |    Login


Powered by UltraApps Forum created with CodeCharge Studio
Copyright © 2003-2004 by UltraApps.com  and YesSoftware, Inc.