How to upload an html file using jsp and jdbc
Hi,
im trying to upload an html page using JSP and jdbc. but of no success.
my aim is to keep some important html pages in the database.the file size can vary.the file has to be selected from a local machine (through the browser) and uploaded to a remote machine(where the databse resides).
any help/sample code or pointer to any helpful link is appreciated.
thanks in advance
javajar2003
When uploading a file, I use a byte array as a temporary buffer..
So, you should then be able to store the byte array in the
database as binary data.
example>
//Temporary Buffer To Store File
byte[] tmpbuffer = new byte[860];
//Some Code To Upload File...
//File Should Now Be In Byte Array
//Get DB Connection and execute Prepared Statement
Connection con=//GET DB CONNECTION;
String sql=insert into TABLE(page) values(?);
PreparedStatement ps=con.prepareStatement(sql);
ps.setBytes(1,tempbuffer);
ps.executeUpdate();
//Close PS and Free DB Connection
..... and this method looks like you dont even have
to store the file in a byte array, you can just give
it the input stream.
ps.setBinaryStream(int, inputStream, int);
You may have to make several attempts at this. I have
uploaded a file and temporarily stored it in a byte array,
but have never from there stored it in the DB as binary
data.. but this looks like it'll work.
Good Luck!
Similar Messages
-
How to upload a image file using JSP
hello to all.
i am in the learning stage please help me to upload a image file
using jsp. give the explanation to the code also if possible.
thanks in advance
sincerely
ChezhianYou may find the following articles useful for the JSP/Servlet part:
Uploading files: http://balusc.blogspot.com/2007/11/multipartfilter.html
Downloading files: http://balusc.blogspot.com/2007/07/fileservlet.html -
How to upload a graphic file using JSP?
Thanks
The same way you upload any other file. Your form must be declared with multipart/form-data encoding and then, upon the form submit, you will have to parse a multipart request. There are a bunch of libraries around that do that. Our product, TICL (at http://www.kobrix.com) includes a server-side FileUpload component that does it and there a few free, special purpose ones that may help too - do an internet search ;)
-
I would like to upload a excel file using jsp
Hi,
I would like to upload the excel file using jsp in my netbeans ide. Please help.
I don Know what is the error in this jsp file. It is not showing any thing and the file is also not getting uploaded.
Please gothru the code below.
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ page import="java.io.*" errorPage="err.jsp"%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="<html:rewrite page="/design.css" />" rel="stylesheet" type="text/css">
<title>Upload Page</title>
</head>
<body onKeyDown="DisablingBackFunctionality()" onLoad="DisablingBackFunctionality()">
<html:form action="download" >
<div style="position:absolute; left:100;top:200;">Select an excel File :<input type="file" name="uploadfile"></div>
<div style="position:absolute; left:190;top:250;"><input type="submit" name="Submit" value="Read"></div>
<div style="position:absolute; left:336;top:250;"><input type="reset" name="Reset" value="Clear"></div>
mainmenu
</html:form>
</body>
</html>
<%
String contentType = request.getContentType();
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);
//out.println("<br> file :"+file);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
//out.println("<br> savefile :"+saveFile);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
//out.println("<br> now file1 :"+saveFile);
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
//out.println("<br> now file2 :"+saveFile);
//out.print(dataBytes);
String ext = "";
if (saveFile.indexOf(".") != -1) {
ext = saveFile.substring(saveFile.lastIndexOf("."));
int lastIndex = contentType.lastIndexOf("=");
//out.println("<br>lst index of"+lastIndex);
String boundary = contentType.substring(lastIndex + 1, contentType.length());
//out.println("<br> boundary"+boundary);
//out.println("<br> file :"+file);
int pos;
pos = file.indexOf("filename=\"");
//out.println("<br> now 0 :"+pos);
pos = file.indexOf("\n", pos) + 1;
//out.println("<br>now 1 :"+pos);
pos = file.indexOf("\n", pos) + 1;
//out.println("<br>now 2 :"+pos);
pos = file.indexOf("\n", pos) + 1;
//out.println("<br>now 3"+pos);
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("D:\\" + saveFile);
//FileOutputStream fileOut = new FileOutputStream(saveFile);
//fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
session.setAttribute("fil", saveFile);
//out.println("File saved as " +saveFile);
%>
<script type="text/javascript" >
function DisablingBackFunctionality()
var URL;
var i ;
var QryStrValue;
URL=window.location.href ;
i=URL.indexOf("?");
QryStrValue=URL.substring(i+1);
if (QryStrValue!='X')
window.location=URL + "?X";
</script>
Please let me know the result as soon as possible. Its my very urgent.
Thanking Yu,
Muthu Kumar.RNo.
Mylenium -
How to upload an excel file using ABAP.
Hi,
Can anyone please help me in understanding how to upload an excel file using ABAP.
Thanks!!http://diocio.wordpress.com/2007/02/12/sap-upload-excel-document-into-internal-table/
check the link
TYPES: Begin of t_record,
name1 like itab-value,
name2 like itab-value,
age like itab-value,
End of t_record.
DATA: it_record type standard table of t_record initial size 0,
wa_record type t_record.
DATA: gd_currentrow type i.
*Selection Screen Declaration
PARAMETER p_infile like rlgrap-filename.
*START OF SELECTION
call function ALSM_EXCEL_TO_INTERNAL_TABLE
exporting
filename = p_infile
i_begin_col = 1′
i_begin_row = 2′ Do not require headings
i_end_col = 14′
i_end_row = 31′
tables
intern = itab
exceptions
inconsistent_parameters = 1
upload_ole = 2
others = 3.
if sy-subrc <> 0.
message e010(zz) with text-001. Problem uploading Excel Spreadsheet
endif.
Sort table by rows and colums
sort itab by row col.
Get first row retrieved
read table itab index 1.
Set first row retrieved to current row
gd_currentrow = itab-row.
loop at itab.
Reset values for next row
if itab-row ne gd_currentrow.
append wa_record to it_record.
clear wa_record.
gd_currentrow = itab-row.
endif.
case itab-col.
when 0001′. First name
wa_record-name1 = itab-value.
when 0002′. Surname
wa_record-name2 = itab-value.
when 0003′. Age
wa_record-age = itab-value.
endcase.
endloop.
append wa_record to it_record.
*!! Excel data is now contained within the internal table IT_RECORD
Display report data for illustration purposes
loop at it_record into wa_record.
write:/ sy-vline,
(10) wa_record-name1, sy-vline,
(10) wa_record-name2, sy-vline,
(10) wa_record-age, sy-vline.
endloop. -
How to parse a HTML file using HTML parser in J2SE?
I want to parse an HTML file using HTML parser. Can any body help me by providing a sample code to parse the HTML file?
Thanks nad Cheers,
AmareshWhat HTML parser and what does "parsing" mean to you?
-
How to download a text file using jsp i
I want to provide download facility in jsp page.
if i have exe download is working . If I have a text / html file it is just displaying I want to make it download How to do it?
regards
subrahmanaymaIf you want to get an "Save as" dialogue, then you need to set the content-disposition in the header to "attachment". The default value is "inline".
Best solution is to create kind of a FileServlet and let it stream the right file as a download to the client. You may find the downloadFile() snippets at the bottom of this article useful: http://balusc.xs4all.nl/srv/dev-jep-pdf.html Put it in a FileServlet and call it using for example . -
Uploading a file using jsp and com.oreilly.servlet lib package
Sorry to bother you but I need your help folks
I am developing an application to pick up files from a database and sent to a specified location on a different system.
I am presently trying to run this code,I have placed this lib package from oreilly which is supposed to encapsulate the usage of file uploads,which is a jar file called cos.jar into C:\Program Files\Java\jdk1.5.0_03\jre\lib\ext folder .I have a jsp page that calls the bean which does the upload and implement the classes in the oreilly package.I am using tomcat 5
[b]the jsp page that acts as the user interface
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Please Choose The File</title>
</head>
<body bgcolor="#ffffff">
<table border="0"><tr>
<form action="Upload.jsp" method="post"
enctype="multipart/form-data">
<td valign="top"><strong>Please choose your document:</strong><br></td>
<td> <input type="file" name="file1">
<br><br>
</td></tr>
<tr><td><input type="submit" value="Upload File"></td></tr>
</form>
</table>
</body>
</html>
this is the jsp page that calls the bean
<jsp:useBean id="uploader" class="com.UploadBean" />
<jsp:setProperty name="uploader" property="dir" value="<%=application.getInitParameter(\"save-dir\")%>" />
<jsp:setProperty name="uploader" property= "req" value="${pageContext.request}" />
<html>
<head><title>file uploads</title></head>
<body>
<h2>Here is information about the uploaded files</h2>
<jsp:getProperty name="uploader" property="uploadedFiles" />
</body>
</html>
[b]this is the bean class
package com;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletRequest;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import javax.servlet.*;
public class UploadBean {
private String webTempPath;
private HttpServletRequest req;
private String dir;
// private ServletRequest request;
public UploadBean( ) {}
public void setDir(String dirName) {
if (dirName == null || dirName.equals(""))
throw new IllegalArgumentException("invalid value passed to " + getClass( ).getName( )+".setDir");
//webTempPath = dirName;
dir = dirName;
/* public String getDir()
return webTempPath;
public void setReq(ServletRequest request) {
if (request != null && request instanceof HttpServletRequest)
req = (HttpServletRequest) request;
} else {
throw new IllegalArgumentException("Invalid value passed to " + getClass( ).getName( )+".setReq");
public String getUploadedFiles( ) throws java.io.IOException{
//file limit size of 5 MB
MultipartRequest mpr = new MultipartRequest(req,dir,5 * 1024 * 1024,new DefaultFileRenamePolicy( ));
Enumeration enume = mpr.getFileNames( );
StringBuffer buff = new StringBuffer("");
for (int i = 1; enume.hasMoreElements( );i++){
buff.append("The name of uploaded file ").append(i).append(" is: ").append(mpr.getFilesystemName((String)enume.nextElement( ))).append("<br><br>");
}//for
//return the String
return buff.toString( );
} // getUploadedFiles
On running the code I find this error messages
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax/servlet/ServletRequest
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.jsp.Upload_jsp._jspService(org.apache.jsp.jsp.Upload_jsp:73)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
java.lang.NoClassDefFoundError: javax/servlet/ServletRequest
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:222)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:151)
com.UploadBean.getUploadedFiles(UploadBean.java:49)
org.apache.jsp.jsp.Upload_jsp._jspService(org.apache.jsp.jsp.Upload_jsp:63)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
Apache Tomcat/5.5.9
tanksHi,
Looks like you are missing a file from the classpath. Make sure servlet.jar is available in your classpath. Ordinarily files in <tomcat_home>/lib directory should be added automatically. You need to check why it hasn't been added in your case. A good place to start would be the bat files in the bin directory viz startup.bat, catalina.bat etc.
cheers,
vidyut -
How to upload a pdf file using webdynpro abap
Hi Experts,
I need to upload pdf files using webdynpro abap.my question is where to upload this files and how to upload this files, and how to display this pdf file.
Please Provide Requried Information.
Waiting for Reply.
Thanks & Regards.
Bhushan.Hi,
There is a UI element with the type 'File Upload'.
You can use that in your view.
For further details and coding, please refer to
[http://www.****************/Tutorials/WebDynproABAP/Upload/Page1.htm]
Hope this helps you.
Regards,
Dolly -
How to upload a .CSV file using GUI_UPLOAD
Hi Experts,
In my report, I need to upload .CSV file using GUI_upload..So how to do ....Plz provide solution...Hi prashanthishetty,
this is already answered many times in this forum!
use forum search or wiki search
[http://wiki.sdn.sap.com/wiki/display/Snippets/uploadcsvfilesintointernal+table]
regards
rea -
How to upload a excel file using BDC
how should i upload a file using BDC
i have downloaded a excel file containing the values of table A006 a X server.
now i hav to upload it into new server Y server using BDC , how do i do it?
wat all things one shud consider ?Hi,
This is very simple, follow the below mention steps to do so:
1.Declare an internal table having same structure as db table, but take all the fields type as 'C' and length same as defined in the table.
TYPES:BEGIN OF it,
key(20) TYPE c,
indicator(20) TYPE c,
bldat(20) TYPE c,"bkpf-bldat
budat(20) TYPE c,"bkpf-budat
END OF it.
DATA: itab TYPE STANDARD TABLE OF it,
wa TYPE it.
2.Include TRUX as type pool and declare a variable of type trux_t_text_data to be passed in the FM that actually reads data from excel sheet into above declared intrenal table.
TYPE-POOLS: truxs.
DATA: it_raw TYPE truxs_t_text_data.
3. Call the FM 'TEXT_CONVERT_XLS_TO_SAP' and pass the file name and the internal table name into the parameter
CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
EXPORTING
* I_FIELD_SEPERATOR = 'X'
i_line_header = 'X'
i_tab_raw_data = it_raw
i_filename = p_file "name of the excel file
TABLES
i_tab_converted_data = itab[] "internal table where data will be stored
EXCEPTIONS
conversion_failed = 1
OTHERS = 2
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
4. loop at internal table and modify the ztable/dbtable where data to be upload .
Hope this solve your problem.
Pooja -
How to mail the html file using javamail????
hi
i have captured the output of a jsp page in a html file....
now i wish to send it in the mail ( *** not as an attachment)
ie
i wish the output of the jsp ie the html file to be displayed in
the message box (ie text area) ..... and then when recieved by the
receipient it shoud be displayed in the message area....
is there any way to do this ........well as said by my fellow poster googling could have given you quick results.
Anyways,if you are unable to do so checkout the below code snippet.
SendMail.java:
===========
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.activation.*;
* @Author RaHuL
* uses SMTP to send Email.
public class SendMail {
/** Method used to read contents of html/text/XML file */
public String readFile(String fileName){
StringBuffer sb = new StringBuffer();
BufferedReader input = null;
try{
input = new BufferedReader(new FileReader(fileName));
String str = null;
while ((str = input.readLine()) != null){
sb.append(line);
}catch(Exception exp){
exp.printStackTrace();
}finally{
try {
if (input!= null)
input.close();
}catch (Exception ex) {
ex.printStackTrace();
return sb.toString();
/** Send an HTML Email with the specific subject to specfic toAddress based on specified fromAddress & Smtp Hostname
* and returns true on success.
public boolean sendMail(String toAddress,String fromAddress,String hostName,String subject,String htmlMessage,String contentType) {
boolean flag = false;
try {
String to = toAddress;
String from = fromAddress;
String host = hostName;
// Setting Mail properties
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.debug","true");
// Getting a New Instance Generated by the API
Session session = Session.getInstance(props);
NOTE: a Mail Session could be configured and could be got from the Container via JNDI
which could be a better practise.
// Instantiate a message
Message msg = new MimeMessage(session);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
// Setting Subject Type
msg.setSubject(subject);
msg.setSentDate(new Date());
// Setting Content Type
msg.setContent(contentType);
// Set message content
msg.setText(htmlMessage);
//Send the message
Transport.send(msg);
flag = true;
}catch (Exception mex) {
// Prints all nested (chained) exceptions as well
mex.printStackTrace();
return flag;
public static void main(String args[]){
SendMail sm = new SendMail();
String htmlMessage = sm.readFile("myHtmlFile.html");
boolean flag = sm.sendMail("[email protected]","[email protected]","your.smtp.server","EMail SubJect",htmlMessage,"text/html");
if(flag)
System.out.println("MAIL SENT SUCCEFULLY");
else
System.out.println("MAIL SENDING FAILURE");
}NOTE:
=====
Make sure you inculde javamail & java activation libraries.
Hope that might help :)
REGARDS,
RaHuL -
How to open a doc file using jsp Anchor tag
when i am trying to open a doc file using a jsp it is opening with out proper alignment.
how to open a doc file with proper alignment using Anchor Tag in JSp Page
Hello!
Does some one of you had open a MS word file (.doc) in Java search for a token like [aToken] replace it with another text and then feed it to a stream of save it?
I want to build a servlet to open a well formatted and rich on media (images) ms word document search for tokens and replace them with information form a web form.
Any Ideas?
Thank you in advanced. -
How to Upload the LDT file Using FND_LOAD for 'MENU','CONCURRENT PROGRAM'
Hi,
I have tried to upload the ldt file in one instance to other instance using the following Command
FNDLOAD apps/apps O Y UPLOAD $FND_TOP/patch/115/import/afsload.lct file_name.ldt MENU MENU_NAME="menu_name"
I got the Output file (LDT file),but I am not able to view in the Application once I upload this again.Same for Concurrent program also.
Can any one help me for solving this issues. Awaiting for your valuable reply.
Thanks,
PrakashYou should probably ask this in an E Business Suite forum.
-
How to retrieve data (xml file) using jsp
I am a newbie to xml. I have decided to store my information in the xml file. may I know how can I retrieve my information from the xml file?
Thanx in advance.I am a newbie to xml. I have decided to store my
information in the xml file. may I know how can I
retrieve my information from the xml file?
Thanx in advance.You can get the information from the XML file using one of the parsers available, such as Xerces http://xml.apache.org, and JDOM as an API.
Using this you have the option of having a SAXParser or a DOMParser.
SAX (Simple API for XML) is an event based parser, so if you know the XML structure, and need to find a certain element, you can just look for the element name,and retrieve the value of the element, it's attributes and its children.
DOM(Document Object Model)represents the XML as a tree, but uses more resources as it stores the entire tree in memory. But it is good in that you can traverse the whole tree.
JDOM would be a good idea too. If you download this, you can use it's API, which is very good, that will use the parser on your system (Xerces). I would definately recommend JDOM.
Maybe you are looking for
-
Camera no longer working in iOS 5 on my iPod touch 4G. I have a black screen when I tap the camera icon. I still have all my photos, but no camara. Any suggestions before I head to the Apple Genius Bar??
-
How do i restore my iphone from "no Service". I tried to update my iphone 3G TO iOS 6.0. But it got stuck and now my itunes is displaying Error message: "there is no sim card installed in the iphone you are attempting to activate" and my iphone is wi
-
Confusion over DBCA script generated for manual RAC DB creation
Version:11.2.0.4/RHEL 6.3 We would like to create our 3-node RAC DB manually. DBCA cannot meet our requirement because our redo log files, datafiles, tempfiles and control files are placed in a complicated manner . If we use DBCA , we will have to s
-
Creating a thread inside doPost
Hello, I have a process which consumes approx 20-30 minutes. I don't want the user to wait till the processing is complete. I would like to display a response as soon as the data is sent to server. So I plan to create an instance of Thread and put th
-
Inteview questions: Please suggest
Hi SAP Gurus I have a few questions, could you please answer them: 1) which of the following is relevant for delivery ; item category or sched line category and why. because both have a check button and what it is significance then. 2) From where doe