Conversión de un archivo del servidor al cliente con servlet

I'm trying to write a servlet, that can upload a file from client to server and download a file from server to client from specific location to specific location. But two problems stopped me: 1. When uploading a file from client to server, how to tell to the server where to store the file? 2. (and more important) How to do the downloading from server to client part?

Aquí está el código hasta ahora:

import java.io.FileOutputStream;  
import java.io.ObjectInputStream;  
import java.io.ObjectOutputStream;  
import java.net.ServerSocket;  
import java.net.Socket;  

 public class Server extends Thread {  
   public static final int PORT = 3333;  
   public static final int BUFFER_SIZE = 100;  

 @Override  
 public void run() {  
     try {  
         ServerSocket serverSocket = new ServerSocket(PORT);  
         while (true) {  
             Socket s = serverSocket.accept();  
             saveFile(s);  
         }  
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
 }  

 private void saveFile(Socket socket) throws Exception {  
     ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  
     ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
     FileOutputStream fos = null;  
     byte [] buffer = new byte[BUFFER_SIZE];    
     Object o = ois.readObject();  

     if (o instanceof String) {  
         fos = new FileOutputStream(o.toString());  
     } else {  
         throwException(null);  
     }  
     Integer bytesRead = 0;  

     do {  
         o = ois.readObject();  

         if (!(o instanceof Integer)) {  
             throwException(null);  
         }  

         bytesRead = (Integer)o;  

         o = ois.readObject();  

         if (!(o instanceof byte[])) {  
             throwException(null);  
         }  

         buffer = (byte[]) o;   
         fos.write(buffer, 0, bytesRead);  
     } while (bytesRead == BUFFER_SIZE);  

     fos.close();  

     ois.close();  
     oos.close();  
 }  

 public static void throwException(String message) throws Exception {  
     throw new Exception(message);  
 }  

 public static void main(String[] args) {  
     new Server().start();  
 }  

}

package com.filetransfer.web;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import javax.servlet.*;
import javax.servlet.http.*;

public class FileTransfer extends HttpServlet {

private static final long serialVersionUID = 1L;
public static final int PORT = 3333;  
public static final int BUFFER_SIZE = 100; 
public static final String HOST = "localhost";

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    String action = request.getParameter("option");
    System.out.println(action);
    if ("upload".equals(action)) {
        uploadFile(request);
    } else if ("download".equals(action)) {
        downloadFile(request, response);
    }
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    doGet(request, response);
}
public void reportError(HttpServletResponse response, String message) throws IOException {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
}

public void uploadFile(HttpServletRequest request) {

    String fileLocation = request.getParameter("localfile");
    File file = new File(fileLocation);

    Socket socket;
    try {
        socket = new Socket(HOST, PORT);
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  

        oos.writeObject(file.getName());  

        FileInputStream fis = new FileInputStream(file);  
        byte [] buffer = new byte[BUFFER_SIZE];  
        Integer bytesRead = 0;  

        while ((bytesRead = fis.read(buffer)) > 0) {  
            oos.writeObject(bytesRead);  
            oos.writeObject(Arrays.copyOf(buffer, buffer.length));  
        }  

        oos.close();  
        ois.close();

    }  catch (Exception e) {
        e.printStackTrace();
    }  
}


 public void downloadFile(HttpServletRequest request, HttpServletResponse response) {

        File file = new File(request.getParameter("remotefile"));
        Socket socket;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            socket = new Socket(HOST, PORT);
            response.setContentLength((int)file.length());
            outputStream = response.getOutputStream();
            inputStream = new BufferedInputStream(new FileInputStream(file));
            int nextByte;
            while ((nextByte = inputStream.read()) != -1) {
                outputStream.write(nextByte);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

preguntado el 09 de enero de 11 a las 00:01

1 Respuestas

Ya que estás usando un HTTP servlet, I strongly suggest to use a HTTP client. Don't pass around proprietary and self-invented request/response formats around, but just construct requests and responses according the HTTP protocol. When you adhere a certain transport standard, then there is no doubt that there are several API's and tools available which may ease the job.

In the client side, you can use java.net.URLConnection or Apache HttpClient for this. Sending files over HTTP from client to server (uploading) usually require a multipart/form-data request encoding. Sending files over HTTP from server to client (downloading) usually require just a correct Content-Type header and the entire file as response body.

En el fondo de esta respuesta you can find an example how to upload files by URLConnection (y en esta respuesta an example with Apache HttpClient 4). In esta respuesta you can find an example how to process the uploaded file in servlet. Saving the uploaded file is easy: just write the obtained InputStream Para algo FileOutputStream. En este artículo you can find an example how to send the file for download. Saving the downloaded file is also easy, just write URLConnection#getInputStream() Para algo FileOutputStream.

contestado el 23 de mayo de 17 a las 15:05

BalusC makes a very important point here. There is no need to re-invent the wheel. - rfeak

Ok, if I want to download a file with filename specified in the URL, I can use a URLConnection. But I want to download a random file from the remote machine on which my server is running. - brain_damage

So your concrete problem is that you don't know how to let the server return a random file? - BalusC

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.