GWT, отображающий изображение, указанное из сервлета

Я использую сервлет для доступа к папке вне веб-контейнера, чтобы загрузить некоторую графику в веб-приложение с помощью GWT. Я использую следующий фрагмент в сервлете, чтобы проверить идею:

        String s = null;
        File inputFile = new File("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(inputFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte c[] = new byte[(int) inputFile.length()];
        try {
            fin.read(c);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fin.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        String imgFolderPath = getServletContext().getRealPath("/")+"img";
        File imgFolder = new File(imgFolderPath);
        imgFolder.mkdir();

        File newImage = new File("megan-fox.jpg");
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(newImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fout.write(c);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean success = newImage.renameTo(new File(imgFolderPath, newImage.getName()));

Код в сервлете считывает файл изображения из указанной папки на жестком диске, создает новую папку с именем «img» в папке war и копирует в нее файл jpg. Затем он возвращает клиенту путь к изображению (на данный момент жестко запрограммированный как) '/img/megan-fox.jpg'. Затем клиент использует класс Image в GWT с возвращенной строкой пути для отображения изображения, как в следующем фрагменте:

public void onSuccess(String result) {
    String myImage = result;
    image = new Image(myImage);
    RootPanel.get().add(image);
    closeButton.setFocus(true);
}

Мне нужно знать, есть ли способ добиться того же результата без использования «промежуточного» шага создания папки в корневом каталоге веб-контейнера (необязательно) и копирования туда файла, чтобы получить к нему доступ с помощью класса Image GWT и отобразить его. ?

обновлено: исходный класс сервлета.

public class GreetingServiceImpl extends RemoteServiceServlet implements
        GreetingService {

    // This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Get the absolute path of the image
        ServletContext sc = getServletContext();
            // i want to load the image in the specified folder (outside the web container)
        String filename = sc.getRealPath("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");

        // Get the MIME type of the image
        String mimeType = sc.getMimeType(filename);
        if (mimeType == null) {
            sc.log("Could not get MIME type of "+filename);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // Set content type
        resp.setContentType(mimeType);

        // Set content size
        File file = new File(filename);
        resp.setContentLength((int)file.length());

        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }

    // This is the method that is called from the client using GWT-RPC
    public String greetServer(String input) throws IllegalArgumentException {
        HttpServletRequest req = this.getThreadLocalRequest();
        HttpServletResponse res = this.getThreadLocalResponse();
        try {
            doGet(req, res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // actually i dont know what that means but i thought i would have to returned something like the image's url?
        return res.encodeURL("/img/image0.png"); 
    }
}

Я логически неправильно использовал метод, который был предложен для решения моей проблемы. Каков правильный путь?


person Fotinopoulos Giorgos    schedule 25.06.2011    source источник


Ответы (1)


Конечно, просто пусть ваш сервлет обслуживает изображение напрямую:

  1. Установите для заголовка Content-Type значение image/jpeg.
  2. Запишите содержимое файла изображения в средство записи ответов сервлета.

Вот пример.

person Peter Knego    schedule 26.06.2011
comment
извините, но я не могу закодировать вашу идею :( Я добавляю метод doPost в свой класс сервлета, но я думаю, что данное имя файла, указанное в ‹strong› String filename = sc.getRealPath(image.jpg) ‹/strong›, связано в корень веб-контейнера. Что делать, если я хочу получить доступ к изображению в папке c:\\myimage.jpg? Может быть, я не понимаю метод, не могли бы вы показать мне, как использовать этот метод в моем классе сервлета, который я включил в моем обновленном первом посте? - person Fotinopoulos Giorgos; 26.06.2011
comment
Этот код является лишь примером — вам не нужно следовать ему буквально. Просто используйте абсолютный путь с файлом: File imageFile = new File("c:\\myimage.jpg") и установите тип контента вручную resp.setContentType("image/jpeg"). - person Peter Knego; 27.06.2011
comment
Ссылка битая - исправьте пожалуйста - person Mr_and_Mrs_D; 01.11.2013