Share on Google+Share on Google+

nikita anand
code required
1 Answer(s)      4 years and 11 months ago
Posted in : Java Beginners

I am making a blog in java using netbeans and database connectivity with SQL Server 2008. I am using JSP pages for the same and not the struts framework I want to provide option for the users to upload a photo(only .jpg,,png etc files) But i am not getting how to provide this option on the JSP page Will you plz help me out by providing me with the code?

Ads

View Answers

May 2, 2012 at 10:19 AM


Jsp Upload Image

1)page.jsp:

<%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD=POST>
<br><br><br>
<center>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<center>
<td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
</tr>
<tr>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send File"> </td>
</tr>
<table>
</center>
</FORM>
</BODY>
</HTML>

2)upload.jsp:

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.zip.*"%>
<%
String saveFile="";
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);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
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;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<% out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){e.printStackTrace();}
}
%>









Related Tutorials/Questions & Answers:
code required.!
Java Script phone number entered by person should be in numeric only. code required!  i am using javascript coding on jsp page. i want that the phone number entered by person should be in numeric only..can i get code
code required
code required  I am making a blog in java using netbeans and database connectivity with SQL Server 2008. I am using JSP pages for the same... page Will you plz help me out by providing me with the code
Advertisements
code required in servlet
code required in servlet  hello... you provided me the answer with javascript.. i want to check which button is clicked in the servlet.. i have only 1 servlet an in that separate codes for different button clicks.. can u plzzz
E BOOK REQUIRED
E BOOK REQUIRED  Wicket in Action pdf required Urgently. Thnx
help required in coding
help required in coding  hi..... I want to display output in graphical format . Can u tell me how it can be done? using for project java swings. plzzzzzz helpp
property datasource required - Spring
property datasource required  Hi I am using java springs I am using mysql as backend I am getting one error when i compile the application.property datasource required. This is my dispatcher-servlet.xml
Help Required - Swing AWT
the password by searching this example's\n" + "source code
Urgently required SEO
Freelance SEO       Position Vacant: Urgently required SEO Job Description ...; Website: http://www.roseindia.net  Reference ID: Urgently required
Hibernate required jar files - Hibernate
Hibernate required jar files  Hi, What are the jar files are required for hibernate and Springs application. I want to run complete application...-spring/index.shtml Download the full code from the above link and extract
steps required to execute a query in JDBC
steps required to execute a query in JDBC  What are the steps required to execute a query in JDBC
Date Format required to change in java
Date Format required to change in java  can we change the format of date like sql as per our requirements???If yes then please give the detail solution
Spring @Required Annotation
Spring @required Annotation In this tutorial you will see about spring @required annotation with an example. The @Required when written on top of setStudent... that org.springframework.beans.factory.BeanInitializationException: Property 'student' is required for bean 'college
Tools required to build Simple Cart
Tools required to build Simple Cart       Shopping cart application is written in Java and so... tools are required--- Java Development Kit (JDK), 1.4 or later. Apache Ant
how to show required fields indicate as * in struts2
how to show required fields indicate as * in struts2  how to show required fields indicate as * in struts2
Why binding attribute is required in jsf frame work
Why binding attribute is required in jsf frame work  Why binding attribute is required in jsf frame work. And what use of binding attribute
jQuery required validation
jQuery required Validation: jQuery "required" is the method...;/option>. Getting Started with jQuery required : In this example there are the following steps which are used to make jQuery required. This example  Makes
Editor help required. - Java Server Faces Questions
Editor help required.  I am having problem with editor used to design JSP page in JSF applications. I want to open JSP page with Web Page Editor... are they? Please Help me.... Thanks In advance
html5 required attribute, Example of required attribute of &lt;textarea&gt; tag in html5
html5 required attribute, Example of required attribute of <textarea> tag in html5 In this tutorial, We will introduce you about the required attribute...; tag: <textarea required="value">Text Here<
Is it required to learn Java before learning Java Script?
Is it required to learn Java before learning Java Script?  Hi, I am beginner and finding information about getting started with Java. The words Java and JavaScript seems similar. Can you explains? Is it required to learn Java
sample JSP&Servlet application required? - JSP-Servlet
sample JSP&Servlet application required?  hey all iam new to jsp&servlets i did read some tutorials about the basics and i want any simple tutorial or a project that integrate both jsp&servlets any help?  Hi Friend
Required help about the concept of JSP page reloading
Required help about the concept of JSP page reloading  Hi, We have one application with Websphere portlet Factory generated JSP as front end, Java in the business layer and finally DB2 as back-end. In certain cases
Required help about the concept of JSP page reloading
Required help about the concept of JSP page reloading  Hi, We have one application with Websphere portlet Factory generated JSP as front end, Java in the business layer and finally DB2 as back-end. In certain cases
HTML5 input autofocus, html5 input required.
HTML5 input autofocus, html5 input required. Introduction:Here we will introduce you to about the autofocus and required attribute of input tag. Type... required autofocus required Automatically focus when page load
The required JDBC drivers to establish connectivity to my database part of the JDK.
The required JDBC drivers to establish connectivity to my database part of the JDK.  Are all the required JDBC drivers to establish connectivity to my database part of the JDK
why do not required application restart after jsp changes?
why do not required application restart after jsp changes?  why do not required application restart after jsp changes? and why in case of class changed
How to install Hibernate-3 and jars required for eclipse environment. And is jboss jars are necessary..?
How to install Hibernate-3 and jars required for eclipse environment... required? I am searching in Google so may jars there some are related jboss... structure and jars required mentioned
code
code  code for android sample program
code
code    how to write this in java
Code
Code  code for connecting c lang to database
code for this is
code for this is  a b c d c b a a b c c b a a b b a a a code
Tutorials   
Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? neo4j-server.properties file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code

Ads

 
Advertisement null

Ads