【问题标题】:get an image from local filesystem from javascript从 javascript 获取本地文件系统的图像
【发布时间】:2015-04-25 21:25:52
【问题描述】:

我正在尝试将图像存储到本地文件系统中。之后,我需要使用 javascript 中的此图像挂载一个 html。

到目前为止,我正在使用 servlet 获取图像,它实际上正在工作,因为我可以在我的 JSP <img width="120" src="<%=IncVars.getParameter("ruta0")%>myImageServlet"> 中显示图像

public class MyImageServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    //get the file image
    File image = IncFunctions.getLogoFile();

    // Get content type
    String contentType = getServletContext().getMimeType(image.getName());

    // Init servlet response.
    response.reset();
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(image.length()));
    // Write image content to response.
    Files.copy(image.toPath(), response.getOutputStream());
}
//...
}

我正在尝试从 js 函数挂载 html,但我找不到在我的 js 函数中使用此图像生成 html 的方法:

 function mountTicket(text, idControl, servletPath){
     document.getElementById(idControl).innerHTML = parseTicket(texto, imagePath);
     window.print();
 }

function parseTicket(texto, servletPath){

var textHtml = "";

 //Call the servlet
 $.get(servletPath, function(data) {
     textoHtml = "<img  width='120' src=" + data + "/>";
     textoHtml += "<br />";
 });    

  //..


  textoHtml += "<div";
  if (estilo != ""){
  textoHtml += " style=\"" + estilo + "\"";
  }         

  textoHtml += ">" + contenido + "</div>";  

  return textoHtml;
}

从 servlet 获取的数据变量是字节,js 似乎不知道如何解释它。我也尝试过传递图像的路径,比如说“C:\myDirectory\myImage.png”,但正如我所料,它找不到并显示它。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: javascript html image file servlets


    【解决方案1】:

    答案比我想象的要容易。我不需要从我的 js 代码中调用 servlet,我只需要添加带有 servlet 路径的图像。 像这样的:

    textoHtml  = "<div><img src='" + servletPath + "'> </div>" ;
    

    浏览器会显示图片。

    希望它可以帮助有类似“问题”的人

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2014-01-04
      • 2018-10-20
      • 1970-01-01
      • 2012-10-24
      相关资源
      最近更新 更多