Docstoc

Uploading FIle Using JSP

Document Sample
Uploading FIle Using JSP Powered By Docstoc
					Uploading File In Java

JSP Example

Uploading File Using JSP
Uploading File Using JSP , First We have to Create Simple HTML page First We will create the simple.html page

Simple.html
<html> <head> <title> FILE UPLOADING USING JSP </title> </head> <body> <form action=“uploading_file.jsp” method=“post” enctype="multipart/form-data">

<table>
<tr> <td><strong>Select File:</strong><br></td> <td> <input type="file" name=“sample"></td> </tr>

<tr><td><input type="submit" value="Upload"></td></tr>
</table> </body> </html>

Creating JSP page for Uploading File : uploading_file.jsp
<%@ page import="java.io.*" %> <% 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); String 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 bound = contentType.substring(lastIndex + 1, contentType.length()); int p;

p= file.indexOf("filename=\""); p= file.indexOf("\n", p) + 1; p= file.indexOf("\n", p) + 1; p= file.indexOf("\n", p) + 1; int boundLoc = file.indexOf(bound, p) - 4; int startPage = ((file.substring(0, p)).getBytes()).length; int endPage = ((file.substring(0, boundLoc)) .getBytes()).length; FileOutputStream fileOut = new FileOutputStream(saveFile); fileOut.write(dataBytes, startPage, (endPage - startPage)); fileOut.flush(); fileOut.close(); out.println(“file uploaded successfully :” + saveFile); %>


				
DOCUMENT INFO
Shared By:
Stats:
views:126
posted:1/21/2010
language:English
pages:4