【问题标题】:How to display image from local path from jsp如何从jsp的本地路径显示图像
【发布时间】:2014-06-20 22:23:28
【问题描述】:

我正在尝试显示图像 throw jsp。图像存储在本地路径中,因此我编写了一个 servlet 获取方法来检索图像,并在图像标记的 src 属性中,我将 servlet 名称和图像路径作为参数提供给 servlet,这是我的代码,

public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
 public void init() throws ServletException {

    this.filePath = "/files";
}

protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do get");

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do post");

}


private static void close(Closeable resource) {
    if (resource != null) {
        try {
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail it.
            e.printStackTrace();
        }
    }
}

在web.xml中servlet入口如下,

<servlet>
<description>
</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.mypackage.FileServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>

在 Jsp 中我有如下 img 标签,

<img alt="Image" src="file/D:/uploads/img14.jsp" width="160" height="160"    class="img-thumbnail">

我认为我在 img 标签的 src 属性中犯了错误,谁能告诉我在这里犯了什么错误。

【问题讨论】:

  • 那是你应该能够自己调试的东西。使用您的调试器,甚至 System.out.printlns,了解 requestedFilefile 的值是什么。当心使用这种 servlet 可能会打开的巨大安全漏洞。您不想让任何用户访问您服务器上的任何文件。此外,.jsp 是一个奇怪的图像扩展名。

标签: java html image jsp servlets


【解决方案1】:

你的 img 标签的 src 属性应该像这样发送请求到你的 servlet。 src="${pageContext.request.contextPath}/FileServlet/getImage?path=D:\offline_registration\11022017\unzip\a89a89e9-5de2-4bb2-9225-e465bb5705b1.jpeg"

这里的路径变量包含来自本地系统的图像路径。

【讨论】:

    【解决方案2】:

    我尝试了下面的代码,它在 servlet 和 java 中都可以正常工作。如果使用下面的代码在servlet中将图像转换为字节,则在会话属性中设置转换后的字节码并获取jsp。

    注意:可以显示任何格式的图片

    package Jx_Test;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    
    import org.apache.commons.codec.binary.Base64;
    
    public class Imag {
    
        public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
            // TODO Auto-generated method stub
             File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
    
                FileInputStream fis = new FileInputStream(file);
                //create FileInputStream which obtains input bytes from a file in a file system
                //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
    
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                try {
                    for (int readNum; (readNum = fis.read(buf)) != -1;) {
                        //Writes to this byte array output stream
                        bos.write(buf, 0, readNum); 
                        System.out.println("read " + readNum + " bytes,");
                    }
                } catch (IOException ex) {
                   // Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
                }
    
                byte[] bytes = bos.toByteArray();
    
                byte[] encodeBase64 = Base64.encodeBase64(bytes);
                String base64Encoded = new String(encodeBase64, "UTF-8");
    
    
                System.out.println(base64Encoded);
        }
    
    }
    
    //Jsp
    <img src="data:image/jpeg;base64,<%=base64Encoded%>"/>
    

    【讨论】:

      【解决方案3】:

      您似乎误解了 BalusC 的帖子:FileServlet。在这种情况下,您的磁盘中将有一个用于服务器文件的基本路径(在服务器中的 Web 应用程序文件夹路径之外),然后您的 URL 中使用的路径将用于搜索内部这个基本路径。请注意 BalusC 的示例如何调用资源:

      <a href="file/foo.exe">download foo.exe</a>
      

      地点:

      • file 是 Servlet 的 URL 模式。在您的 web.xml 配置中注明:

        <servlet-mapping>
        <servlet-name>FileServlet</servlet-name>
        <url-pattern>/file/*</url-pattern>
        </servlet-mapping>
        
      • URL /foo.exe 的其余部分是文件在服务器硬盘中的位置。这可以通过使用HttpServletRequest.html#getPathInfo

      • 轻松获得

      这部分代码说明了这一点(cmets 是我的):

      public void init() throws ServletException {
          this.filePath = "/files";
      }
      
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          // Get the file path from the URL.
          String requestedFile = request.getPathInfo();
      
          //...
          //using filePath attribute in servletclass as the base path
          //to lookup for the files, using the requestedFile
          //path to seek for the existance of the file (by name)
          //in your server
          //decoding the name in case of GET request encoding such as
          //%2F => /
          File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
          //...
      }
      

      然后,当有这样的请求时(在您的视图中的 HTML 代码中):

      <img src="files/img/myimage.png" />
      

      您必须确保该文件存在于您的服务器中:

      - /  <-- root
        - /files <-- this is the base file path set in init method in your servlet
          - /img
            - myimage.png
      

      更多信息:

      【讨论】:

      • 没有。 ,我不明白你在说什么,请告诉我我的 src 属性值应该是什么,或者告诉我是否需要更改 FileServlet 中的任何内容?
      • 我在本地驱动器中说我的图像,我的意思是在 D:/uploads/Img.jpg 路径中​​。
      • @user3599482 我说过这对于您的 Servlet 没关系不要在没有阅读和理解的情况下粗心/盲目地在网上复制/粘贴一些代码。我什至发布了一个示例,说明如何放置 &lt;img src=""&gt; 以及 servlet 填充试图找到它的位置。如果您知道您的所有文件都将在 D:/uploads 中,则将您的服务器中的 filePath 值从 "/files" 更改为 "D:\\uploads"
      【解决方案4】:

      您犯的错误是试图将您的 JSP 页面调用为图像资源。 JSP 本身只是一个文本文件。您需要将文件的路径替换为服务器上将编译/提供 JSP 页面结果(即图像)的页面的 url。如果它在本地服务器上,通常 url 看起来像 http://localhost:&lt;port&gt;/.../img14.jsp

      【讨论】:

      • 你能告诉我,我的 servlet 对吗?在 servlet 中,文件路径变量将存储什么。我不明白。
      • 是的,我的意思是图像的src 属性必须指向为图像提供服务的url,而不是指向JSP 文件本身。虽然我无法调试您的代码,但我认为文件路径必须指向实际的图像文件。
      • k 。 .当我在调试中运行它时,我收到 404 错误,因为它正在进入 (!file.exists()) 块。
      • 那说明你的图片路径不对,或者图片文件不存在。
      • 在调试模式下运行时,在 (!file.exists()) 文件 obj 中显示路径为 '\file\D:\uploads\img014.jpg' 所以它正在进入 if 块和抛出 404 错误
      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2016-10-01
      • 2011-11-16
      • 2012-05-17
      相关资源
      最近更新 更多