Programacion web con j2ee y jsp's

Ami go!
Como puedo subir en un sitio web un archivo o imajen desde el cliente y que la mande al servidor y como la descargo ; basicamente quiero que aparesca una ventanita como cuando descargas cualkquier archivo y te pregunta si lo quieres abrir o guardar en tu disco duro.
No se si se hace por ftp o http: me gustaria si fuese por ambos.
El sitio web lo constryyo con j2ee, jsp y servlets, etc.

1 respuesta

Respuesta
1
Bien, veo que son dos preguntas, una como envío un fichero del cliente al servidor y otra como lo envío del servidor al cliente. Empezaré por la segunda, ya que es más sencilla.
Para que un cliente recoja un fichero desde el servidor solo tienes que crear un link a dicho fichero. Suponte que el fichero lo tienes en un directorio llamado "download" que cuelga de la raiz de tu sitio. En la página web debes poner:
<a href="/download/nombrefichero.ext">pincha aqui para descargar</a>
El navegador se encargará de descargar el archivo y preguntarte si deseas abrirlo o guardarlo.
Para enviar un archivo al servidor es algo más complicado. Necesitas un servlet que recoja el ficheros y crear una página web para que el cliente diga que fichero quiere enviar, lo más importante es:
1.- En la página web crear un formulario que llame al servlet que se encarga de recoger el archivo. Este formulario DEBE ser de tipo "multipart/form-data" y enviar con método post:
<form name="miformulario" action="regocgeFichero.jsp" enctype="multipart/form-data" method="POST">
2.- En la página web crear un objeto "input" de tipo fichero:
<input type="file" name="fichero">
3.- Respecto al servlet, te envío al final uno que creo es bastante autoexplicativo.
Espero haberte ayudado. Un saludo.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class UploadServlet2 extends HttpServlet {
static final int Max = 102400;// max. size of the file can be 100K
String path;// stores path
String msg;// store message of success
//init method is called when servlet is first loaded
public void init(ServletConfig config)throws ServletException {
super.init(config);
if(path == null)
path = "S:/web/";
if(msg == null)
msg = "File successfully uploaded. Check out!";
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream sos = null;
DataInputStream dis = null;
FileOutputStream fos = null;
try {
resp.setContentType("text/plain");// return type of response is being set as plain
sos = resp.getOutputStream();// gets handle to the output stream
} catch(IOException e) {
System.out.println(e);
return;
}
try {
String contentType = req.getContentType();// gets client's content type that should be multipart/form-data
if(contentType!=null && contentType.indexOf("multipart/form-data")!= -1) {
// gets handle to the input stream to get the file to be uploaded from client
dis = new DataInputStream(req.getInputStream());
// gets length of the content data
int Length = req.getContentLength();
if(Length>Max) { // length of the content data is compared with max size set
sos.println("sorry! file too large");
sos.flush();
return;
}
//to store the contents of file in byte array
byte arr[] = new byte[Length];
int dataRead = 0;
int totalData = 0;
while(totalData <Length) {
dataRead = dis.read(arr,totalData,Length);
totalData += dataRead;
}
String data = new String(arr);//byte array converted to String
arr = null;
// gets boundary(límite) value
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex+1,contentType.length());
String dir = "";
if(data.indexOf("name=Directory")>0) { // the type ""Directory"" is searched in the web page
dir = data.substring(data.indexOf("name=Directory"));
//gets directory
// the directory higher in the directory tree cannot be selected
if(dir.indexOf("..")>0) {
sos.println("Error- the directory higher in the directory tree cannot be selected");
return;
}
}
String successPage="";
if(data.indexOf("name="SuccessPage"")>0) { // the type ""SuccessPage"" is searched in the web page
successPage =data.substring(data.indexOf("name="SuccessPage""));
// gets successpage
}
String overWrite="";
if(data.indexOf("name="OverWrite"")>0) { // the type ""Overwrite"" is searched in the web page
overWrite =data.substring(data.indexOf("name="OverWrite""));
overWrite = overWrite.substring(overWrite.indexOf("
")+1);
overWrite = overWrite.substring(overWrite.indexOf("
")+1);
overWrite = overWrite.substring(0,overWrite.indexOf("
")-1);//gets overwrite flag
} else {
//overWrite = "false";
}
String overWritePage ="";
if(data.indexOf("name="OverWritePage"")>0) {
// the type ""OverwritePage"" is searched in the web page
// ensures same file is not uploaded twice
overWritePage =data.substring(data.indexOf("name="OverWritePage""));
overWritePage = overWritePage.substring(overWritePage.indexOf("
")+1);
overWritePage = overWritePage.substring(overWritePage.indexOf("
")+1);
overWritePage = overWritePage.substring(0,overWritePage.indexOf("
")-1);// // gets overwritepage
}
//gets upload file name
String file =data.substring(data.indexOf("filename="")+10);
file = file.substring(0,file.indexOf("
"));
file = file.substring(file.lastIndexOf("\")+1,file.indexOf("""));
int position;//upload file's position
position =data.indexOf("filename="");//find position of upload file section of request
position =data.indexOf("
",position)+1;//find position of content-disposition line
position =data.indexOf("
",position)+1;//find position of content-type line
position =data.indexOf("
",position)+1;//find position of blank line
int location =data.indexOf(boundary,position)-4;//find position of next boundary marker
data =data.substring(position,location);// uploaded file lies between position and location
String fileName = new String(path + dir + file);// the complete path of uploadad file
File check = new File(fileName);
/*************************CASE OVERRIDE ************************************/
//String overwrite=req.getParameter("OverWrite");
if(check.exists()) { // checks for existence of file
if(overWrite.equals("false")) {
if(overWritePage.equals("")) {
sos.println("Sorry ,file already exists");
//return;
}
} else {
//overWritePage="G:/Workspace/overwritepage.html";
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
//resp.sendRedirect(overWritePage);
sos.println("File Overridden");
}
//return;
}
File checkDir = new File(path + dir);
if(!checkDir.exists()) { //checks for existence of directory
checkDir.mkdirs();
}
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
sos.println("File successfully uploaded");
if(check.exists()) {
if(overWrite.equals("true")) {
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
if(successPage.equals("")) {
sos.println(msg);
sos.println("File successfully uploaded");// if success HTML page URL not received
} else {
successPage="S:/web/successpage.html";
resp.sendRedirect(successPage);
}
}
}
} else {// incase request is not multipart
sos.println("Not multipart");
}
} catch(Exception e) {
try {
System.out.println(e);
sos.println("unexpected error");
} catch(Exception f) {
System.out.println(f);
}
} finally {
try {
fos.close();// file output stream closed
dis.close();// input stream to client closed
sos.close();// output stream to client closed
} catch(Exception f) {
System.out.println(f);
}
}
}//END OF DOPOST METHOD
} //END OF CLASS

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas