** Subiendo archivos al servidor desde jsp **

Para un requerimiento me pidieron que el sistema pudiera subir archivos de cualquier tipo, para lo cual una muy buena opción que encontré en la web es : UploadBean la cual tiene unos ejemplos muy buenos y sencillos de configurar,bueno hasta este momento jeje.
Una vez que la descarguen necesitaran agregar los .jar al proyecto, si es Netbeans seleccionar “Libraries-Add Jar” y seleccionas : UploadBean.jar, cos.jar, fileupload.jar, también tiene soporte para struts y ahi mismo viene la libreria, bueno hecho lo anterior, en el folder que han descargado viene varios ejemplos , abran el de DatabaseUpload y les va a mostrar un código como este:
<html>
<%@ page language=”java” import=”javazoom.upload.*,java.util.*” %>
<%@ page errorPage=”ExceptionHandler.jsp” %><jsp:useBean id="upBean" scope="application" class="javazoom.upload.UploadBean" >
<%
Properties props = new Properties();
// Modify info below to fit to your database settings.
props.put("user","scott");
props.put("password","tiger");
upBean.setDatabasestore("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@MYSERVER:1521:ORCL", props);
// If you have get a JDBC Connection from a javax.sql.DataSource
// Then use upBean.setDatabasestore(YourConnection);
// Also, uncomment and modify variables below if you need to map to your own database schema.
//UploadBean.SQLUPLOADTABLE = "UPLOADS";
//UploadBean.SQLUPLOADID = "UPLOADID";
//UploadBean.SQLUPLOADFILENAME = "FILENAME";
//UploadBean.SQLUPLOADFILE = "BINARYFILE";
// Note that if you need to modify SQL request then see UploadBean
// add-ons section to plug a custom DBStore implementation (BLOB, ...).
%>
</jsp:useBean>
<jsp:setProperty name="upBean" property="overwrite" value="true" /><head>
<title>Samples : Database Upload</title>
<style TYPE="text/css">
<!--
.style1 {
font-size: 12px;
font-family: Verdana;
}
-->
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<ul class="style1">
<%
if (MultipartFormDataRequest.isMultipartFormData(request))
{
// Uses MultipartFormDataRequest to parse the HTTP request.
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
String todo = null;
if (mrequest != null) todo = mrequest.getParameter("todo");
if ( (todo != null) && (todo.equalsIgnoreCase("upload")) )
{
Hashtable files = mrequest.getFiles();
if ( (files != null) && (!files.isEmpty()) )
{
UploadFile file = (UploadFile) files.get("uploadfile");
if (file != null) out.println("<li>Form field : uploadfile"+"<BR> Uploaded file : "+file.getFileName()+" ("+file.getFileSize()+" bytes)"+"<BR> Content Type : "+file.getContentType());
// Store uploaded files in database now. Third parameter allows to pass options Map.
HashMap options = null;
// Sample advanced options.
//options = new HashMap();
//options.put("dbstore.uploadid","id."+System.currentTimeMillis());
//options.put("dbstore.filesize","enabled");
//options.put("dbstore.filetype","enabled");
//options.put("dbstore.customcolumn.created_date",new Date());
upBean.store(mrequest, "uploadfile", options);
// int lastid = ((DefaultDBStore)upBean.getDatabasestoreimplementation()).getLastId();
}
else
{
out.println("<li>No uploaded files");
}
}
else out.println("<BR> todo="+todo);
}
Vector history = upBean.getHistory();
int amount = 0;
if (history != null) amount = history.size();
%>
<br><i>(Uploaded files : <%= amount %>)</i>
</ul>
<form method="post" action="DatabaseUpload.jsp" name="upform" enctype="multipart/form-data">
<table width="60%" border="0" cellspacing="1" cellpadding="1" align="center" class="style1">
<tr>
<td align="left"><b>Select
a file to upload :</b></td>
</tr>
<tr>
<td align="left">
<input type="file" name="uploadfile" size="50">
</td>
</tr>
<tr>
<td align="left">
<input type="hidden" name="todo" value="upload">
<input type="submit" name="Submit" value="Upload">
<input type="reset" name="Reset" value="Cancel">
</td>
</tr>
</table>
<br>
<br>
<table border="0" cellspacing="1" cellpadding="0" align="center">
<tr>
<td bgcolor="#666666">
<table width="100%" border="0" cellspacing="1" cellpadding="0" align="center" class="style1">
<tr>
<td bgcolor="#FFFFFF"><b><font color="#0000FF">
HTML tags used in this form :</font></b></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"> <<b>form</b>
<b>method</b>="<b><font color="#FF0000">post</font></b>"
<b>action</b>="<b><font color="#FF0000">DatabaseUpload.jsp</font></b>"
name="upload" <b>enctype</b>="<b><font color="#FF0000">multipart/form-data</font></b>"></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"> <<b>input</b>
<b>type</b>="<b><font color="#FF0000">file</font></b>"
<b>name</b>="<font color="#FF0000"><b>uploadfile</b></font>"
size="50"></td>
</tr>
</table>
</td>
</tr>
</table>
<p> </p>
<p> </p>
<p align="center"> </p>
<p align="center"> </p>
<p align="center"><font size="-1" face="Courier New, Courier, mono">Copyright
© <a href="http://www.javazoom.net" target="_blank">JavaZOOM</a> 1999-2006</font></p>
</form>
</body>
</html>
De todo ese churro la parte importante y a configurar es:
<html>
<%@ page language="java" import="javazoom.upload.*,java.util.*" %>
<%@ page errorPage="ExceptionHandler.jsp" %><jsp:useBean id="upBean" scope="application" class="javazoom.upload.UploadBean" >
<%
Properties props = new Properties();
// Modify info below to fit to your database settings.
props.put("user","scott");
props.put("password","tiger");
upBean.setDatabasestore("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@MYSERVER:1521:ORCL", props);
// If you have get a JDBC Connection from a javax.sql.DataSource
// Then use upBean.setDatabasestore(YourConnection);
// Also, uncomment and modify variables below if you need to map to your own database schema.
//UploadBean.SQLUPLOADTABLE = "UPLOADS";
//UploadBean.SQLUPLOADID = "UPLOADID";
//UploadBean.SQLUPLOADFILENAME = "FILENAME";
//UploadBean.SQLUPLOADFILE = "BINARYFILE";
// Note that if you need to modify SQL request then see UploadBean
// add-ons section to plug a custom DBStore implementation (BLOB, ...).
%>
</jsp:useBean>
<jsp:setProperty name="upBean" property="overwrite" value="true" />
Por default hay que correr un script que viene en la página ya citada, pero si tu necesitas hacer un insert a tu propia base, solo tiene que quitarle los comentarios a los segmentos de UploadBean.
UploadBean.SQLUPLOADTABLE = seleccionar la base de datos
UploadBean.SQLUPLOADID= nombre del campo "id" para el archivo
UploadBean.SQLUPLOADFILENAME= nombre del campo donde ira el nombre del archivo
UploadBean.SQLUPLOADFILE= nombre del campo donde se va almacenar el archivo, que para mysql es del tipo longblob.
Ahora, esta libreria te genera un propio "id" para la imagen, si tu quieres que inserte tu propio id ya sea de una sesión o cualquier variable y te vas una linea mas abajo que están comentadas, le quitas los comentarios y
options.put("dbstore.uploadid",);
Y sustituye "id."+System.currentTimeMillis() por tu variable.
Y es todo, creo que no esta muy complicado y con esa libreria puedes subir carpetas, imagenes, mp3, .zip.
Archivado en: Uncategorized | 13 Comments

y domo hago para descargar el archivo si al poner Ir
buscará el archivo en el disco del usuario y no del servidor
Buenas tardes alfaquino se que es un poco tarde pero quisiera saber si diste con la solucion, sino te puedo ayudar.
ok ya lo he probado yo y jala bien al subir a la bd, pero podrias decirme alguna idea o ejemplo de como recuperar el archivo al parecer creo que beanupload tienen sus metodos pero todavia no investigo bien investigue para hacerlo desde recuperacion desde un archivo temporal desde el disco local del server y de ahi mostrarlo como se hace aqui: http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=uploadJSF
pero me gustaria hacerlo todo con beanupload, gracias, espero que puedas contestarme, saludos desde puebla, mexico.
my bueno el ejemplo era justo l oque necesitaba corre perfecto
Gracias
hola tengo el bean corriendo si alguien sabe que se necesita pra recuperar los datos con las clases del JSP y pueda informarme lo agradecieria mucho
bueno yo tengo la base en Mysql y no m corre bien lo unico q me muestra es los datos del archivo ya cambie la conexion y no m funciona alguien m puede ayudar
This post is genuinely a nice one it helps new
web users, who are wishing in favor of blogging.
Howdy! I realize this is kind of off-topic however I needed to ask.
Does managing a well-established blog such as yours take a massive amount work?
I’m completely new to writing a blog but I do write in my diary everyday. I’d like to start a blog so I
can share my own experience and views online. Please let me know
if you have any ideas or tips for brand new aspiring bloggers.
Appreciate it!
Hi there, i read your blog from time to time and
i own a similar one and i was just curious if you get a lot of spam comments?
If so how do you protect against it, any plugin or
anything you can recommend? I get so much lately it’s driving me insane so any assistance is very much appreciated.
While booking a Paphos Car Hire for the Annaurna circuit trekking
7. Therefore all you can do during your trip. The record for the largest Leyland paphos car hire Leylandii tree is a
natural hybrid. 00/day when you pick up at the airport.
At last count, Mr.
Someone necessarily assist to make severely articles I might state.
That is the very first time I frequented your website page and so far?
I amazed with the analysis you made to create this actual submit
incredible. Magnificent process!
I think what you wrote made a great deal of sense.
But, think about this, what if you typed
a catchier post title? I ain’t saying your content isn’t solid.
, however what if you added a headline that grabbed
folk’s attention? I mean ** Subiendo archivos al servidor desde jsp ** | Aumakua:tikiti tikiti y regresamos a Mty! is kinda vanilla. You should look at Yahoo’s home page and note how they create news titles to grab
people interested. You might add a video or a related pic or two to
get people interested about everything’ve got to say. Just my opinion, it could bring your website a little bit more interesting.
hello!,I love your writing very a lot! share we keep in touch more approximately your article on AOL?
I require an expert on this house to resolve my problem.
May be that is you! Looking ahead to see you.