Documentos de Académico
Documentos de Profesional
Documentos de Cultura
com.oreilly.servlet
, adems solo se explican los elementos mnimos necesarios para hacerlo. Lo primero
que hay que conocer es lo bsico de HTML para crear un formulario que permita
seleccionar un archivo, escribir su ruta en un campo de texto y enviarlo al servidor.
El formulario (form)
Lo primero que hay que especificar con las caractersticas del formulario importantes:
Dentro del formulario se necesita un elemento input de tipo file y un simple botn para
activar la accin del formulario. el cdigo podra verse as:
/*
* uploadFichero.java
*
* Created on 4 de agosto de 2003, 22:26
*/
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.util.*;
/**
*
* @author Roberto Canales
* @version
*/
public class uploadFichero extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
System.out.println("Comenzamos procesamiento ficheros");
procesaFicheros(request,out);
out.println("</body>");
out.println("</html>");
out.close();
}
void depura(String cadena)
{
System.out.println("El error es " + cadena);
}
public boolean procesaFicheros(HttpServletRequest req, PrintWriter
out ) {
try {
// construimos el objeto que es capaz de parsear la
pericin
DiskFileUpload fu = new DiskFileUpload();
// maximo numero de bytes
fu.setSizeMax(1024*512); // 512 K
depura("Ponemos el tamao mximo");
// tamao por encima del cual los ficheros son escritos
directamente en disco
fu.setSizeThreshold(4096);
File("c:\\ficherossubidos\\" +
}
}
2. In the upload() method, create a FormData interface instance, and add the
file element with the attached file into it. Use the send() method to send the
FormData to the server.
3. <script>
4.
var client = new XMLHttpRequest();
5.
6.
function upload()
7.
{
8.
var file = document.getElementById("uploadfile");
9.
10.
/* Create a FormData instance */
11.
var formData = new FormData();
12.
/* Add the file */
13.
formData.append("upload", file.files[0]);
14.
15.
client.open("post", "/upload", true);
16.
client.setRequestHeader("Content-Type", "multipart/formdata");
17.
client.send(formData); /* Send to server */
18.
}
19.
20.
/* Check the response status */
21.
client.onreadystatechange = function()
22.
{
23.
if (client.readyState == 4 && client.status == 200)
24.
{
25.
alert(client.statusText);
26.
}
27.
}
</script>
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.OutputStream;
import
import
import
import
import
javax.servlet.ServletContext;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment;
filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
}
}
Configure URL mapping for this servlet in the web deployment descriptor file web.xml
as follows:
<servlet>
<description>This servlet sends file to client</description>
<display-name>DownloadFileServlet</display-name>
<servlet-name>DownloadFileServlet</servlet-name>
<servlet-class>net.codejava.DownloadFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadFileServlet</servlet-name>
<url-pattern>/DownloadFileServlet</url-pattern>
</servlet-mapping>
On submission of request to upload the file, our servlet program will upload the file into
a directory in the server and then provide the URL through which user can download
the file. For security reason, user will not be provided direct URL for downloading the
file, rather they will be given a link to download the file and our servlet will process the
request and send the file to user.
We will create a dynamic web project in Eclipse and the project structure will look like
below image.
Lets look into all the components of our web application and understand the
implementation.
ServletContextListener implementation
Since we need to read context parameter for file location and create a File object from
it, we can write a ServletContextListener to do it when context is initialized. We can set
absolute directory location and File object as context attribute to be used by other
servlets.
Our ServletContextListener implementation code is like below.
package com.journaldev.servlet;
import java.io.File;
import
import
import
import
javax.servlet.ServletContext;
javax.servlet.ServletContextEvent;
javax.servlet.ServletContextListener;
javax.servlet.annotation.WebListener;
@WebListener
public class FileLocationContextListener implements
ServletContextListener {
public void contextInitialized(ServletContextEvent
servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStream;
java.io.PrintWriter;
java.util.Iterator;
java.util.List;
import
import
import
import
import
import
import
javax.servlet.ServletContext;
javax.servlet.ServletException;
javax.servlet.ServletOutputStream;
javax.servlet.annotation.WebServlet;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
org.apache.commons.fileupload.FileItem;
org.apache.commons.fileupload.FileUploadException;
org.apache.commons.fileupload.disk.DiskFileItemFactory;
org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/UploadDownloadFileServlet")
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
@Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File)
getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or
empty");
}
File file = new
File(request.getServletContext().getAttribute("FILES_DIR")+File.separa
tor+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on
server.");
}
System.out.println("File location on
server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null?
mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;